Recipe 20.3. Printing a Stack Trace

20.3.1. Problem

You want to know what's happening at a specific point in your program, and what happened leading up to that point.

20.3.2. Solution

Use debug_print_backtrace( ):

function stooges() {   print "woo woo woo!\n";   larry(); } function larry() {   curly(); } function curly() {   moe(); } function moe() {   debug_print_backtrace(); } stooges();

This will print:

woo woo woo! #0  moe() called at [backtrace.php:14] #1  curly() called at [backtrace.php:10] #2  larry() called at [backtrace.php:6] #3  stooges() called at [backtrace.php:21]

20.3.3. Discussion

The debug_backtrace( ) function was introduced in PHP 4.3.0, followed by the handy debug_print_backtrace( ) function in PHP 5.0.0. This combination allows you to quickly get a sense of what has been been going on in your application immediately before you called a particular function.

The more complicated your application, the more information you can expect to have returned from the backtrace functions. For debugging larger codebases, you may achieve bug-hunting success more quickly using a full debugging extension, such as Xdebug, or an integrated development environment (IDE), such as PHPEdit or Zend Studio, that supports setting breakpoints, stepping in and out of blocks of code, watching the evolution of variables, and more.

If all you need is a little more information than you can get from sprinkling print 'Here I am on line ' . __LINE__; statements throughout your code, debug_backtrace( ) and/or debug_print_backtrace( ) will suit your needs well.

If you're still using PHP 4 and want the PHP 5only debug_print_backtrace( ) function, you can use PEAR's PHP_Compat compatibility package. PHP_Compat provides an implementation of debug_print_backtrace( ) that is identical to the native PHP 5 function.

20.3.4. See Also

Documentation on debug_backtrace( ) at and on debug_print_backtrace( ) at; the PEAR PHP_Compat package at; Zend Studio IDE at; PHPEdit IDE at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: