0

I'm trying to load a template in print_table() function. If I uncomment the include_once code above, it will work. Why? the get_template function does exactly the same. As it is now it says $people is undefined.

function get_template( $template_name ) {
include_once __DIR__ . DIRECTORY_SEPARATOR . $template_name;
}

function print_table( $people ) {
// include_once __DIR__ . DIRECTORY_SEPARATOR . 'html/table.php';
get_template( 'html/table.php' );
}

in html/table.php

<table>
<tr>
    <th>Name</th>
    <th>Author</th>
    <th>Date</th>
</tr>
<?php dd($people); ?>
</table>
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
Svetlozar
  • 967
  • 2
  • 10
  • 23

3 Answers3

3

The included file is evaluated in the scope of the function including it. print_table has a variable $people in scope. get_template does not, since you're not passing the variable to get_template; it only has a $template_name variable in scope.

Also see https://stackoverflow.com/a/16959577/476.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

$people is an argument of function print_table(), that's why it is available in the file included by print_table().

But it is not available in the file included by the get_template() function because in the context of the get_template() function there is no variable named $people defined.

Read about variable scope.

axiac
  • 68,258
  • 9
  • 99
  • 134
1

That's because of variable scope. $people is not defined in your function get_template() (as well said in other answers).

To be reusable, you also could pass an associative array that contains all variables and use extract() to use them as variable in your template:

function get_template($template_name, $data) {
    extract($data);
    include_once __DIR__ . DIRECTORY_SEPARATOR . $template_name;
}

function print_table($people) {
    get_template('html/table.php', ['people'=>$people]);
}
Syscall
  • 19,327
  • 10
  • 37
  • 52