且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

包含的PHP文件可以知道包含它的位置吗?

更新时间:2023-09-19 23:23:58

$_SERVER['PHP_SELF'] 将包含当前正在执行的脚本,无法从包含的文件中确定哪个特定的脚本导致了包含.

While $_SERVER['PHP_SELF'] will contain the currently executing script, there is no way to determine from an included file which specific script caused the include.

这意味着,如果a.php包括b.php,其中包括c.php,则c.php将无法知道b.php是包含者.***的结果是a.php是当前正在执行的脚本.

This means that if a.php includes b.php, which includes c.php, c.php will have no way of knowing that b.php was the includer. The best you can get is that a.php is the currently executing script.

是的,我上面的答案在技术上是错误的-您可以使用 debug_backtrace 查找调用方,即使没有功能也要直到PHP 5.4删除该功能.

Yup, my above answer is technically wrong -- you can use debug_backtrace to find the caller, even without functions, up until PHP 5.4, which removes this functionality.

a.php:

<?php
echo 'A';
include 'b.php';

b.php:

<?php
echo 'B';
include 'c.php';

c.php:

<?php
echo 'C';
print_r(debug_backtrace());

输出:

ABCArray
(
    [0] => Array
        (
            [file] => /tmp/b.php
            [line] => 3
            [function] => include
        )

    [1] => Array
        (
            [file] => /tmp/a.php
            [line] => 3
            [args] => Array
                (
                    [0] => /tmp/b.php
                )

            [function] => include
        )

)

因此,尽管此方法有效,但您可能不应该使用它.过度使用 debug_backtrace可能会明显降低性能.

So while this works, you probably shouldn't use it. debug_backtrace can be a noticeable performance drag when used excessively.