Backtracing with PHP Part 2Backtracing with PHP Part 2

Posted December 24th, 2009 in PHP

A week ago I looked at how to do a backtrace with PHP using the debug_backtrace function which returns an array containing a lot of information, and the debug_print_backtrace function which provides more concise information but always sends it to standard output. In this post I show how to capture the information from debug_print_backtrace into a string and an alternative method using the Exception object.

Using debug_print_backtrace with output buffering

My last PHP post looked at output buffering with PHP and how to use the ob* functions to start buffering and how to capture output into a string. Using these functions it is possible to capture the output from the debug_print_backtrace function into a string without it displaying on a webpage.

ob_start();
debug_print_backtrace();
$backtrace = ob_get_clean();

Using the Exception object

A simpler method than using the output buffering functions, and which ensures the existing buffers are not affected, is to use the Exception object's getTraceAsString method instead.

$e = new Exception();
$backtrace = $e->getTraceAsString();

The information returned by the getTraceAsString() method is more or less the same as that for the debug_print_backtrace() function and is easier than having to mess around with ob* functions. Note that it cannot be called statically so calling Exception::getTraceAsString() will result in an error ("Fatal error: Non-static method Exception::getTraceAsString() cannot be called statically").

Related posts:

Comments

blog comments powered by Disqus