PHP: backtracing function names - useful for logging and debugging
July 19th, 2007 by smoove
Today i want to show you a little trick that allows you to backtrace function calls (finding out which function called the function you are currently in)
Lets start with an example script, i will explain the details below.
{
logIt('Log Message...');
return;
}
function logIt($msg)
{
// this is where the magic happens:
$backtrace = debug_backtrace();
//demo: output log to browser
echo '<b>Log Message:</b> "' . $msg . '" - in file <b>' . $backtrace[1]['file'] . '</b> Line: <b>' . $backtrace[1]['line'] . '</b> - Function: <b>' . $backtrace[1]['function'] . '()</b><br /><br />';
//it is a good idea to also output/log the arguments given to that function - very nice for debugging
echo '<b>Arguments:</b><br />';
// parse all arguments
foreach($backtrace[1]['args'] as $argument)
{
echo '* ' . $argument . '<br />';
}
}
getThisName('This is argument 1', 'This is argument 2');
This will output:
<strong>Arguments:</strong>
* This is argument 1
* This is argument 2
So, what the above script does is:
- function getThisName() is called
- getThisName() calls function logIt()
- logIt() loads the result of debug_backtrace in an array
- logIt() outputs the result
How it works
debug_backtrace() will return an array that looks like this:
(
[0] => Array
(
[file] => /var/www/site/tracing.php
[line] => 4
[function] => logIt
[args] => Array
(
[0] => Log Message...
)
)
[1] => Array
(
[file] => E:roottracing.php
[line] => 27
[function] => getThisName
[args] => Array
(
[0] => This is argument 1
[1] => This is argument 2
)
)
)
So as you can see you have one array with multiple arrays in it, every array represents one level.
The array with the key [0] is always the function that calls debug_backtrace() - in our case logIt(), the lowest level.
Key [1] is one level above the one that is calling debug_backtrace() - in our case getThisName(). If there a more levels, there will be more arrays, one for every level.
So you could say $backtrace[2] to get the details of th function that called getThisName.
This means you can backtrace very complex function calls, wich will help you to debug your php scripts.
I hope this information was useful for you, i use it pretty often since i found out about this great php feature.






