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

时间:2009-12-20 13:46:39

标签: php function debugging

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

例如,

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

6 个答案:

答案 0 :(得分:34)

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

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


例如,temp.php包含此内容:

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

并且temp-2.php包含此内容:

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


从我的浏览器中调用temp.php (i.e. the first script)可以获得此输出:

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

在那里,我有“temp.php”文件名 - 这是调用该函数的文件名。


当然,你需要再测试一下(特别是在函数不在“第一级”包含文件的情况下,但在另一个文件中包含的文件中 - 不确定debug_backtrace会有很多帮助,那里......);但这可能会帮助你获得第一个想法...

答案 1 :(得分:5)

试试这个:

$key = array_search(__FUNCTION__, array_column(debug_backtrace(), 'function')));
var_dump(debug_backtrace()[$key]['file']);

答案 2 :(得分:3)

除了Pascal Martins的建议外,您还可以安装PECL扩展程序APD并使用apd_callstack()之类的内容(引用示例)

// returns an array containing an array of arrays.

Each array appears to contain:
[0] = function name
[1] = filename that contains function
[2] = *calling* line number in *calling* file
[3] = An array which is usually empty

但由于这是PECL扩展并且可能会干扰Zend Optimizer,因此最好使用debug_backtrace()。

答案 3 :(得分:0)

您可以将文件名作为参数传递:

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

当你调用该函数时,你传递了魔法常量 FILE

sthing(__FILE__);

答案 4 :(得分:0)

2行-完成:

$backfiles=debug_backtrace();
echo $file_called_from=$backfiles[0]['file']; // complete filepath

或者仅裁剪文件名,添加以下内容

echo "<Br>";
echo basename($file_called_from); // for only the filename without the path

答案 5 :(得分:0)

这会打印出 file_name:line

function myFunction() {
  $backfiles = debug_backtrace();
  echo $backfiles[0]['file'] . ':' . $backfiles[0]['line'];
}
相关问题