我正在使用ob_get_contents()
作为核心方法创建自己的模板脚本。通过使用它,它可以渲染出其他文件,从一个文件调用。
就像,假设我们有4个文件:
- index.php
- header.html
- 页脚.html
- functions.php
index.php
将调用并呈现其他文件的内容(此处为2个html文件)。通过使用以下代码:
//index.php
function render($file) {
if (file_exists($file)) {
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
echo render('header.html');
echo render('footer.html');
但是(例如)当header.html
包含调用include('functions.php')
时,包含的文件(functions.php)不能在footer.html
中再次使用。我的意思是,我必须在footer.html
中再次加入。所以在这里,include('functions.php')
行必须包含在这两个文件中。
如何include()
文件而不从子文件再次调用它?
当您使用ob_start()
(输出缓冲)时,您最终只能得到文件的输出,这意味着执行输出的文件由ob_get_content()
返回。由于只返回其他文件不知道包含的输出。
所以答案是:你不能用输出缓冲来实现这一点。或者用include_once
启动ob_start之前的include
文件。
它可以像这样工作:
//index.php
function render($file) {
if(!isset($GLOBALS['included'])) {
$GLOBALS['included'] = array();
}
if (!in_array($file, $GLOBALS['included']) && file_exists($file)) {
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
$GLOBALS['included'][] = $file;
return $content;
}
}
echo render('header.html');
echo render('footer.html');
或者,您可以使用includeonce(include_once $file;
),PHP将为您执行此操作。
尽管我建议您确保文件加载结构的形状不会发生这些事件。