PHP: debug_backtrace vs. debugger call stack

Remember that we explicitly added the line starting with #BP: using magic constants.

WTF?resolutionPHP’s debug_backtrace() function works differently than some folks would expect since it is reporting the specific line/function name that is calling the next stack frame rather than the enclosing function scope as you might see in a debugger or other similar contexts.

If I were to rearrange the output to appear more intuitively (for me) and compare the two directly, it would look something like this:Notice that in order to get results similar to my “standard” call stack, you would have to index into one row of the debug_backtrace() output for the class and function name and then index into the next row up of that output for the file name and line number.

For example, in order to simulate my row #1 (line 11) from the “standard” call stack above you would index into row #1 (line 5) for the class and function but you’d look at row #0 (line 4) for the file name and line number.

comparisonOther debug trace tools do not work the way debug_backtrace() works in PHP.

For example, this is the output from Python’s traceback.

print_stack() function when applied to a port of the example code above: File "c.

py", line 10, in <module> CClass.

c_function('param') File "c.

py", line 8, in c_function BClass.

b_function(1, 'two') File "/data/tmp/html/b.

py", line 18, in b_function AClass.

a_function(True) File "/data/tmp/html/a.

py", line 27, in a_function traceback.


stdout)Here we have similar information output as {file}{line no.

}{enclosing scope}.

The actual line of code (that is calling the next stack frame) is shown on the next line by itself.

This format is nice because it presents the location of the stack frame all on one line and it allows another entire line for code itself.

conclusionThe output from PHP’s debug_backtrace() function is counter-intuitive if you are coming from a debugger or another language like Python.

However, all the information you are looking for is there if you rearrange it a little to suit yourself.

Knowing this, I may write a debug_print_stack() utility function for PHP which indexes into different places, uses magic constants, and includes clear comments to explain exactly why.

.. More details

Leave a Reply