PHP:如何检查给定文件是否已包含在函数中()


PHP: how to check if a given file has been included() inside a function

我有一个PHP文件,可以包含在另一个页面的不同位置。我想知道它是否已包含在函数中。我该怎么做?谢谢。

> 有一个名为 debug_backtrace() 的函数,它将当前调用堆栈作为数组返回。这感觉像是一个有点丑陋的解决方案,但它可能适用于大多数情况:

$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
    // ignore calls to include/require
    if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
        echo 'File has not been included in the top scope.';
        exit;
    }
}

您可以在包含的文件中设置一个变量,并在函数中检查该变量:

包括.php:

$included = true;

另一个文件.php:

function whatever() {
    global $included;
    if (isset($included)) {
        // It has been included.
    }
}
whatever();

您可以检查文件是否在 get_included_files() 返回的数组中。(请注意,列表元素是完整路径名。若要查看在特定函数调用期间是否包含,请检查函数调用前后的get_included_files。