Print PHP Stack Trace

I was having a bit of trouble tracking down exactly where a method was getting called from today.

Usually a search in my project directory will turn up the result very quickly, but I wasn’t having luck with PHPStorm for some reason.

So, the next best thing was to get a stack trace so that I could get the last few functions that had been run. I don’t do stack traces much in PHP, so I had to track down the code to use.

Of the few options to use, this seemed to be the easiest to use and remember.

$e = new Exception;

// Output the stack trace to the browser
echo $e->getTraceAsString();

// Send stack trace to error log
error_log( $e->getTraceAsString() );

And if you’re wanting more verbose output, including the arguments that were passed to each function, try this.

$e = new \Exception;

// Recursively print the stack trace
print_r( $e->getTrace() );

// Log the stack trace object
error_log( print_r( $e->getTrace(), true ) );

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading