I have been developing in PHP from the last 4-5 years. Since the introduction of OOP concepts in PHP5, the language is getting matured and more ready for large applications.
While working with large projects, one can not avoid logging for error / debug to later diagnose the issues one might face in production. So beside logging some general information and simple errors which PHP throws and we could get from PHP we could also capture the whole backtrace for the code we are running in such case.
It could be easily incorporated in your application. Follow are some modified examples from PHP’s documentation debug_print_backtrace:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
//This is backtrace_include.php //This function modifies the output which PHP provides for debug_print_backtrace //by dany dot dylan at gmail dot com function debug_string_backtrace() { ob_start(); debug_print_backtrace(); $trace = ob_get_contents(); ob_end_clean(); // Remove first item from backtrace as it's this function which // is redundant. $trace = preg_replace ('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1); // Renumber backtrace items. $trace = preg_replace ('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace); return $trace; } function a() { return b(); } function b() { return c(); } function c() { return debug_string_backtrace(); } $trace = a(); echo $trace; |
Save the above file as backtrace_include.php and call in the following file:
1 2 |
//This is backtrace_test.php include 'backtrace_include.php'; |
This will print the following:
1 2 3 4 |
#0 c() called at [/home/www/backtrace_include.php:29] #1 b() called at [/home/www/backtrace_include.php:24] #2 a() called at [/home/www/backtrace_include.php:37] #3 include(/home/www/backtrace_include.php) called at [/home/www/backtrace_test.php:3] |
Usually in production websites, we don’t print such trace on screen and log this in a file. We will also log such information only in a situation when an error occurs while executing the code.