Svetlozar
Svetlozar

Reputation: 987

Variable in template is undefined

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>

Upvotes: 0

Views: 132

Answers (3)

Syscall
Syscall

Reputation: 19780

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]);
}

Upvotes: 1

axiac
axiac

Reputation: 72177

$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.

Upvotes: 1

deceze
deceze

Reputation: 522005

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.

Upvotes: 3

Related Questions