0

I'm using PHP for web development. I'm using the following function to wrap the include of a view:

<?php
function render($templateFile) {
    $templateDir = 'views/';
    if (file_exists($templateDir . $templateFile)) {
        include $templateDir . $templateFile;
    } else {
        throw new Exception("Template '{$templateFile}' couldn't be found " .
           "in '{$templateDir}'");
    }
}
?>

Although this seems right to me, there is a really unexpected behavior: when I define a variable to something (e.g. an array) and use render for including a view that uses that variable, I get an undefined variable error. But when I explicitely use include there is no error at all and things are just fine.

This is the script that calls render:

<?php
include 'lib/render.php'; // Includes the function above.

$names = array('Trevor', 'Michael', 'Franklin');

render('names.html'); // Error, but "include 'views/names.html'" works fine.
?>

And this is the file that uses the $names variable:

<html>
  <head>
    <title>Names</title>
  </head>
  <body>
    <ol>
    <?php foreach ($names as $name): ?>
      <li><?php echo $name; ?></li>
    <?php endforeach; ?>
    </ol>
  </body>
</html>

Help will be very much appreciated.

7
  • wouldn't it error anyway if you pass an array to the function, since you're not iterating through the array in your function.
    – kennypu
    May 25, 2014 at 1:50
  • Try to avoid using include and prefer include_once, although that will only give a warning. I think it is best practise (ymm) to always use require_once so that you will know immediately if the referenced file cannot be accessed. May 25, 2014 at 2:05
  • $templatePath = $templateDir . $templateFile; include $templatePath;
    – volkinc
    May 25, 2014 at 2:21
  • @volkinc Whether you post it as an answer or as a comment, it's still not necessary to do it that way (it works just fine as is), and it doesn't solve the problem.
    – Cully
    May 25, 2014 at 2:22
  • 1
    @Cully Larson, you are right. this is a scope problem
    – volkinc
    May 25, 2014 at 2:30

2 Answers 2

2

This is from the PHP documentation on the include function (c.f. https://www.php.net/manual/en/function.include.php):

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

And also:

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

So, if your render function can't access $names, then neither can your included file.

A possible solution would be to pass the parameters you want to be able to access in your view template, to your render function. So, something like this:

function render($templateFile, $params=array()) {
    $templateDir = 'views/';
    if (file_exists($templateDir . $templateFile)) {
        include $templateDir . $templateFile;
    } else {
        throw new Exception("Template '{$templateFile}' couldn't be found " .
           "in '{$templateDir}'");
    }
}

Then, pass them like this:

$names = array('Trevor', 'Michael', 'Franklin');

render('names.html', array("names" => $names));

And use them in your view template like this:

<html>
  <head>
    <title>Names</title>
  </head>
  <body>
    <ol>
    <?php foreach ($params['names'] as $name): ?>
      <li><?php echo $name; ?></li>
    <?php endforeach; ?>
    </ol>
  </body>
</html>

There are probably better solutions to this, like putting your render function into a View class. Then you can call the View class function from inside your template file, and access parameters that way instead of just assuming there will be a $params variable in the view templates scope. But, this is the simplest solution.

1
  • I feel kinda awful because reading the docs more carefully could've save me the error, but thank you a lot anyways. I'm definitely marking this as the right answer. As for the approach in rendering the views I know that encapsulating in a class is way better, but this is a code that's intended to help with development of students in a software engineering course focusing on structured programming (no OO yet) in which I'm TA.
    – oxfist
    May 25, 2014 at 3:44
1

The problem is, when you include the file directly using include 'views/names.html' the variable $name remains in the same files scope. Hence, it works. But when the include is done through the function, the varibale $name remains out of scope inside the function. So it doesn't work. For example, declare $names as global inside the function and it will work.

If you update the function like below you will see $names variable works.

function render($templateFile) {

    global $names; // declares the global $names variable to use in the included files

    $templateDir = 'views/';
    if (file_exists($templateDir . $templateFile)) {
        include $templateDir . $templateFile;
    } else {
        throw new Exception("Template '{$templateFile}' couldn't be found " .
           "in '{$templateDir}'");
    }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.