debug_backtrace and FILE/LINE indices

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all,

I've been using debug_backtrace() for a while to provide stack traces
for a custom logging function. Today was the first time I've got the
following error:

"Notice: Undefined index: file in E:\webroot\lib\errors.php on line

Notice: Undefined index: line in E:\webroot\lib\errors.php on line

related to the following code:

      $vDebug = debug_backtrace();
      $vFiles = array();
      for ($i=0;$i<count($vDebug);$i++) {
         // skip the first one, since it's always this func
         if ($i==0) { continue; }
         $aFile = $vDebug[$i];
         $vFiles[] = '('.basename($aFile['file']).':'.
       } // for
       return implode(',',$vFiles);

I checked the PHP documentation for this function, and to my surprise
found that:

"The *possible* returned elements are as follows:", ie: 'file' and
'line' wont always be returned. When are these elements returned, so
that I can make the function do something useful when file/line isn't



Re: debug_backtrace and FILE/LINE indices

Also sprach Taras_96:

Quoted text here. Click to load it

A workaround: If 'file' and 'line' are not returned, use the respective  
values from the next entry in the backtrace array. Here's what I use:

  $aTrace = debug_backtrace();
  // Loop backwards (!) through array
  for ( $sFile = '', $iLine = 0, $i = count( $aTrace ); $i--; )
   // Make sure all fields are set
    = array_merge(
      'function' => '',
      'type'     => '',
      'class'    => '',
      'object'   => array(),
      'args'     => array(),
      'file'     => $sFile,
      'line'     => $iLine

   // Add this for convenience
    = $aTrace[$i]['class']
    . $aTrace[$i]['type']
    . $aTrace[$i]['function'];

   // Missing file or line? Copy from previous item
   $sFile = $aTrace[$i]['file'];
   $iLine = $aTrace[$i]['line'];

  // Remove first item ("this function")
  array_shift( $aTrace );

This way, all possible fields are set to useful values. If you're only  
interested in file and line, you can optimize the code of course.


Re: debug_backtrace and FILE/LINE indices

Thanks Thomans, I'll try out your suggestion and see how it goes :).


On Apr 25, 5:01 am, "Thomas Mlynarczyk" <tho...@mlynarczyk-> wrote:
Quoted text here. Click to load it

Site Timeline