我知道函数debug_backtrace,但我正在寻找一些准备使用函数的实现,如GetCallingMethodName()?如果它也给出了方法的类(如果它确实是一个方法),那就太完美了。
当前回答
我所见过的这个问题的最佳答案是:
list(, $caller) = debug_backtrace(false);
简洁明了
其他回答
对我来说,debug_backtrace达到了内存限制,我想在生产中使用它来记录和发送发生的错误。
相反,我发现这个解决方案非常有效!
// Make a new exception at the point you want to trace, and trace it!
$e = new Exception;
var_dump($e->getTraceAsString());
// Outputs the following
#2 /usr/share/php/PHPUnit/Framework/TestCase.php(626): SeriesHelperTest->setUp()
#3 /usr/share/php/PHPUnit/Framework/TestResult.php(666): PHPUnit_Framework_TestCase->runBare()
#4 /usr/share/php/PHPUnit/Framework/TestCase.php(576): PHPUnit_Framework_TestResult->run(Object(SeriesHelperTest))
#5 /usr/share/php/PHPUnit/Framework/TestSuite.php(757): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#6 /usr/share/php/PHPUnit/Framework/TestSuite.php(733): PHPUnit_Framework_TestSuite->runTest(Object(SeriesHelperTest), Object(PHPUnit_Framework_TestResult))
#7 /usr/share/php/PHPUnit/TextUI/TestRunner.php(305): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#8 /usr/share/php/PHPUnit/TextUI/Command.php(188): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#9 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true)
#10 /usr/bin/phpunit(53): PHPUnit_TextUI_Command::main()
#11 {main}"
你也可以使用php异常提供的信息,这是一个优雅的解决方案:
function GetCallingMethodName(){ $e = new Exception(); $trace = $e->getTrace(); //position 0 would be the line that called this function so we ignore it $last_call = $trace[1]; print_r($last_call); } function firstCall($a, $b){ theCall($a, $b); } function theCall($a, $b){ GetCallingMethodName(); } firstCall('lucia', 'php');
你会得到这个…(瞧!)
Array ( [file] => /home/lufigueroa/Desktop/test.php [line] => 12 [function] => theCall [args] => Array ( [0] => lucia [1] => php ) )
我最喜欢的方式,一句话!
debug_backtrace()[1]['function'];
你可以这样使用它:
echo 'The calling function: ' . debug_backtrace()[1]['function'];
注意,这只与去年发布的PHP版本兼容。但出于安全考虑,让PHP保持最新是一个好主意。
从php 5.4开始就可以使用
$dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
$caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;
这不会浪费内存,因为它忽略参数,只返回最后2个回溯堆栈条目,并且不会像这里的其他答案一样生成通知。
我需要一些东西来列出调用类/方法(在Magento项目上工作)。
虽然debug_backtrace提供了大量有用的信息,但它为Magento安装提供的信息量是压倒性的(超过82,000行!)因为我只关心调用函数和类,所以我想出了这个小解决方案:
$callers = debug_backtrace();
foreach( $callers as $call ) {
echo "<br>" . $call['class'] . '->' . $call['function'];
}
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 我如何调试git/git-shell相关的问题?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- Visual Studio拒绝忘记断点?
- 如何从对象数组中通过对象属性找到条目?