获取运行 PHP 的文件的文件名包括

2022-01-25 00:00:00 include php

当使用 PHP include 时,我如何知道是哪个文件调用了 include?简而言之,父文件filename是什么?

When using the PHP include, how can I find out which file is calling the include? In short, what is the parent's file filename?

推荐答案

一个简单的方法是在父文件中分配一个变量(在包含之前),然后在包含的文件中引用该变量.

An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.

父文件:

$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';

包含的文件:

if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";

<小时>

您也可以使用 get_included_files()debug_backtrace() 并找到包含文件的时间和位置的事件,但这可能会有点混乱和复杂.


You could also mess around with get_included_files() or debug_backtrace() and find the event when and where the file got included, but that can get a little messy and complicated.

相关文章