PHP:您可以通过函数传递包含内容吗?

时间:2019-02-05 22:34:24

标签: php include

是否可以通过功能包含文件?我的意思不是将内容作为字符串返回。我想创建自己的自定义include方法,但是现在看来这是不可能的。

例如,PHP的 include 方法输出文件内容。我想输出文件内容,但是首先要通过另一个函数运行它们。

例如:

function include_filter($file){
    include($file);
}
include_filter($file);

此示例未使用其他功能,因为我的主要问题是如何通过一个函数来包含所有内容。您可以看到问题。

如果我通过 include_filter 之类的函数包含代码,则该代码将仅本地包含在函数内部,而不是在函数被调用的那一行(第4行该示例)。

1 个答案:

答案 0 :(得分:0)

include语句不输出文件内容。但是,它会评估您要包含的文件,因此,如果该文件包含任何echo语句,那么是的,那些语句将在您包含该文件时立即执行。

您可以使用输出缓冲区来捕获该输出并对其进行某些操作,然后再重新echo使用它:

included_file.php

<?php
echo "This came from an included file.";

main_file.php

<?php
function include_filter($path) {
    ob_start();
    include $path;
    $output = ob_get_contents();
    ob_end_clean();

    echo str_replace("an included file", "a filter function", $output);
}

include_filter("included_file.php");
// will output "This came from a filter function."

演示:https://3v4l.org/2XkL7