找到在PHP中调用我的函数的文件名

问题描述:

如何查找调用函数的脚本的文件名?

How do I find out the filename of the script that called my function?

例如,

function sthing() {
echo __FILE__; // echoes myself
echo __CALLER_FILE__; // echoes the file that called me
}


p>解决方案可能是使用 debug_backtrace 功能:在回溯中,应该存在这种信息。

A solution might be to use the debug_backtrace function : in the backtrace, that kind of information should be present.

或者,正如戈登在评论中指出的,你也可以使用 debug_print_backtrace 如果您只想输出该信息,而不能使用它。

Or, as Gordon pointed out in a comment, you can also use debug_print_backtrace if you just want to output that information and not work with it.



例如,使用 temp。包含以下内容的php

<?php
include 'temp-2.php';
my_function();

temp-2.php 这个:

<?php
function my_function() {
    var_dump(debug_backtrace());
}



调用 temp。 (即第一个脚本)从我的浏览器得到我的输出:


Calling temp.php (i.e. the first script) from my browser gets me this output :

array
  0 => 
    array
      'file' => string '/.../temp/temp.php' (length=46)
      'line' => int 5
      'function' => string 'my_function' (length=11)
      'args' => 
        array
          empty

在那里,我有$ code> temp.php filename - 这是调用函数的那个​​。

In there, I have the "temp.php" filename -- which is the one in which the function has been called.



当然,你必须再测试一下(特别是在功能不在第一级包含的文件中,但在另一个文件中包含的文件中) - 不确定 debug_backtrace 将帮助很多,那里...);但这可能有助于您获得第一个想法...


Of course, you'll have to test a bit more (especially in situations where the function is not in the "first level" included file, but in a file included by another one -- not sure debug_backtrace will help much, there...) ; but this might help you get a first idea...