Backtracing Function Calls

ShawnCplus 0 Tallied Votes 77 Views Share

So you've got this big long function chain and PHP's oh-so-helpful Fatal Error messages aren't helping at all. Here's a quick example of how to do a function backtrace without throwing exceptions.

Output:

=>[0] => Array
  (
    [file] => someFile.php
    [line] => 4
  )
=> Hello World
<?php
function foo()
{
  $blah = bar('hello');
  echo $blah;
}
 
function bar($foo)
{
  // $function_calls will contain the entire backtrace of calls to `bar`
  // $current_call will contain information for the latest call to `bar`
  $function_calls = array();
  foreach(debug_backtrace() as $key=>$value) {
    if($value['function'] == __FUNCTION__) {
      $function_calls[] = array('file'=>$value['file'], 'line'=>$value['line']);
    }
  }
  $current_call = $function_calls[0];
  print_r($current_call);
  return $foo.' World';
}

foo();
?>