【问题标题】:(PHP) How to pass the previous INCLUDE / REQUIRE calls into child files?(PHP) 如何将之前的 INCLUDE / REQUIRE 调用传递给子文件?
【发布时间】:2012-03-21 23:04:36
【问题描述】:

我正在使用ob_get_contents() 作为核心方法创建自己的模板脚本。通过使用它,它可以渲染出其他文件,从一个文件中调用。

就像,假设我们有 4 个文件:

  • index.php
  • header.html
  • footer.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()一个文件而不从子文件中再次调用它

【问题讨论】:

    标签: php include require ob-get-contents


    【解决方案1】:

    当你使用ob_start()(输出缓冲)时,你只会得到文件的输出,这意味着文件执行的输出由ob_get_content()返回。由于仅返回其他文件不知道包含的输出。

    所以答案是:你不能用输出缓冲来做到这一点。或者 include 你的文件在 ob_start 之前使用 include_once

    【讨论】:

    • ob_start 之前将我的文件包含在include_once 中吗?哦,所以对于我的例子,如果我在index.php 的顶部用include_once 声明所有必要的文件是可能的。这样孩子就不用再申报了吧?
    • @4lvin 是的,当然有可能。您可以在开头使用include_oncerequire_once,您的所有子文件都会看到包含的内容。
    • 哇!是的!这很简单,令人难以置信!!干杯并感谢Arman P.
    【解决方案2】:

    这可以像这样工作:

    //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');
    

    您也可以使用include_once (include_once $file;),PHP 会为您完成。

    虽然我建议您确保文件加载结构的形状不会发生这些事件。

    【讨论】:

    • 我可以只声明一次include_once,在index.php 文件的最顶部(在渲染子文件之前),而不是使用你的方式$GLOBALS?求知识。
    • 是的,你可以。但更好的是确保一个文件永远不会被包含两次,无论调用什么文件。
    猜你喜欢
    • 2011-04-12
    • 2012-01-18
    • 2015-10-25
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多