[英]Variable in template is undefined
I'm trying to load a template in print_table()
function. 我正在尝试在print_table()
函数中加载模板。 If I uncomment the include_once code above, it will work. 如果我取消注释上面的include_once代码,它将起作用。 Why? 为什么? the get_template function
does exactly the same. get_template function
作用完全相同。 As it is now it says $people is undefined. 现在它说$ people是不确定的。
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 在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. print_table
在范围内具有变量$people
。 get_template
does not, since you're not passing the variable to get_template
; get_template
不会,因为您没有将变量传递给get_template
; it only has a $template_name
variable in scope. 它的作用域中只有一个$template_name
变量。
Also see https://stackoverflow.com/a/16959577/476 . 另请参阅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()
. $people
是函数print_table()
的参数,这就是为什么它在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. 但它不是由包含在文件中提供get_template()
函数,因为在上下文get_template()
函数没有名为变量$people
定义。
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). $people
没有在您的函数get_template()
定义(在其他答案中也是如此)。
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: 为了可重用 ,您还可以传递一个包含所有变量的关联数组,并使用extract()
将它们用作模板中的变量:
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.