Skip to content

[PHP] Debug Print Call Stack

Let’s say you lost in the middle of a method and difficult to trace which other methods call the current method, you can debug or back trace by following approcah :

1 default / common PHP function to perform back trace, here’s the example

<?php
// include.php file
function firstMethod() {
secondMethod();
}
functions econdMethod() {
thirdMethod();
}
function thirdMethod(){
debug_print_backtrace();
}
firstMethod();

?>

it will print like this

#0  thirdMethod() called at [/tmp/include.php:10]
#1  secondMethod() called at [/tmp/include.php:6]
#2  firstMethod() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

but if the class contains lot of methods or complex method chains, above print it will not show but will show “out of memory”, so this approach only works on less complex class

2.  This second approach basically to solve “out of memory” issue and also more readable to back trace, here’s the example

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

source :
https://www.php.net/manual/en/function.debug-print-backtrace.php
https://stackoverflow.com/questions/1423157/print-php-call-stack

Share

Comments are closed.