Sunday, June 19, 2011

PHP - Getting the Call Stack

So how do you get the call stack of a certain line of PHP code when it is your first time to see it? Well, I believe the first thing that will come to mind for anyone relatively new in programming and PHP will have to mark the line he's at and read/trace the code up manually and see any user-defined function calls, objects creations and file includes then do the same for each file associated.Phew.. some much work. There's an easier way however.

1) Use debug_trace() or debug_print_trace()



This will yield you with all the functions called, the arguments passed to the functions and the references to where they where called.

2) Throw an exception

throw new Exception('just debugging')

Throwing an exception will halt the application and by default print debugging information similar to the above.  The only difference is that you don't have to call another exit command to prevent the script from continuing execution.

In relation to that above, I have seen programmers relying on vigorous, manual work to locate a PHP code problem by using simple methods like print_r, print or echo with an exit code following the command to debug. This is not a bad thing, in fact I do it to myself often. There are however smarter ways to do it for more complex applications which rely on libraries and modules which have better programming design patterns infused to the code than the early-2000 way of one-page-has-everything technique which is still newbie mistake even on the year 2011.

There are ways to be smarter in terms of debugging PHP to boost your productivity many folds. Explore use of IDE debuggers, PHP extension debuggers such DBG, Xdebug, Advance PHP debugger (, things like ZFDebug and FirePHP. It's a topic worth discussing in another article. :)
  • Related Links Widget for Blogspot

No comments: