簡體   English   中英

模板中的變量未定義

[英]Variable in template is undefined

我正在嘗試在print_table()函數中加載模板。 如果我取消注釋上面的include_once代碼,它將起作用。 為什么? get_template function作用完全相同。 現在它說$ 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' );
}

在html / table.php中

<table>
<tr>
    <th>Name</th>
    <th>Author</th>
    <th>Date</th>
</tr>
<?php dd($people); ?>
</table>

在包含它的功能范圍內評估包含的文件。 print_table在范圍內具有變量$people get_template不會,因為您沒有將變量傳遞給get_template 它的作用域中只有一個$template_name變量。

另請參閱https://stackoverflow.com/a/16959577/476

$people是函數print_table()的參數,這就是為什么它在print_table()包含的文件中可用的原因。

但它不是由包含在文件中提供get_template()函數,因為在上下文get_template()函數沒有名為變量$people定義。

了解有關可變范圍的信息

那是因為范圍可變。 $people沒有在您的函數get_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM