我正在寻找一种在PHP中打印调用堆栈的方法。

如果函数刷新IO缓冲区,则加分。


当前回答

看到debug_print_backtrace。我想如果你想的话,你可以之后再喊冲水。

其他回答

奇怪的是没有人这样发帖:

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

这实际上是在没有垃圾的情况下打印backtrace -只是调用了什么方法和在哪里。

看到debug_print_backtrace。我想如果你想的话,你可以之后再喊冲水。

phptrace是一个很好的工具,可以在任何时候打印PHP堆栈,而不需要安装任何扩展。

phptrace有两个主要功能:一是打印PHP调用堆栈,不需要安装任何东西;二是跟踪PHP执行流,需要安装它提供的扩展。

如下:

$ ./phptrace -p 3130 -s             # phptrace -p <PID> -s
phptrace 0.2.0 release candidate, published by infra webcore team
process id = 3130
script_filename = /home/xxx/opt/nginx/webapp/block.php
[0x7f27b9a99dc8]  sleep /home/xxx/opt/nginx/webapp/block.php:6
[0x7f27b9a99d08]  say /home/xxx/opt/nginx/webapp/block.php:3
[0x7f27b9a99c50]  run /home/xxx/opt/nginx/webapp/block.php:10 

记录跟踪

$e = new Exception;
error_log(var_export($e->getTraceAsString(), true));

谢谢@Tobiasz

比debug_backtrace()更具可读性:

$e = new \Exception;
var_dump($e->getTraceAsString());

#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}"