简体   繁体   中英

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>

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM