Archive for the ‘php’ Category

PHP: backtracing function names - useful for logging and debugging

Thursday, July 19th, 2007

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.

function getThisName($arg1, $arg2)
{
  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>Log Message:</strong> "Log Message..." - in file <strong>/var/www/site/tracing.php</strong> Line: <strong>26</strong> - Function: <strong>getThisName()</strong>

<strong>Arguments:</strong>
* This is argument 1
* This is argument 2

So, what the above script does is:

  1. function getThisName() is called
  2. getThisName() calls function logIt()
  3. logIt() loads the result of debug_backtrace in an array
  4. logIt() outputs the result

How it works
debug_backtrace() will return an array that looks like this:

Array
(
  [0] =&gt; Array
  (
    [file] =&gt; /var/www/site/tracing.php
    [line] =&gt; 4
    [function] =&gt; logIt
    [args] =&gt; Array
    (
        [0] =&gt; Log Message...
    )
  )
  [1] =&gt; Array
  (
    [file] =&gt; E:roottracing.php
    [line] =&gt; 27
    [function] =&gt; getThisName
    [args] =&gt; Array
    (
        [0] =&gt; This is argument 1
        [1] =&gt; 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.