Hi, I got tired of using a trace( $message, __FILE__, __LINE__ ) function I made. It forced me to include the file and line params (since php doesn't have macros) so I decided to make an alternative.
Simply call this new version using trace( 'my message' ); and it prints out a stack trace in a clearer way than the one stored in the debug_backtrace() array. It handles traces from outside of functions, traces in nested functions, and traces in included files, and also displays the function in a way that can be pasted right back into your php code for faster testing!
NOTE - be sure to save your files with the correct line endings for the line numbers to work correctly, which for Mac OS X is unix. You can get to this option in the popup menu in the toolbar at the top of each window in BBEdit.
<?php
function print_var( $var )
{
if( is_string( $var ) )
return( '"'.str_replace( array("\x00", "\x0a", "\x0d", "\x1a", "\x09"), array('\0', '\n', '\r', '\Z', '\t'), $var ).'"' );
else if( is_bool( $var ) )
{
if( $var )
return( 'true' );
else
return( 'false' );
}
else if( is_array( $var ) )
{
$result = 'array( ';
$comma = '';
foreach( $var as $key => $val )
{
$result .= $comma.print_var( $key ).' => '.print_var( $val );
$comma = ', ';
}
$result .= ' )';
return( $result );
}
return( var_export( $var, true ) ); }
function trace( $msg )
{
echo "<pre>\n";
$trace = array_reverse( debug_backtrace() );
$indent = '';
$func = '';
echo $msg."\n";
foreach( $trace as $val)
{
echo $indent.$val['file'].' on line '.$val['line'];
if( $func ) echo ' in function '.$func;
if( $val['function'] == 'include' ||
$val['function'] == 'require' ||
$val['function'] == 'include_once' ||
$val['function'] == 'require_once' )
$func = '';
else
{
$func = $val['function'].'(';
if( isset( $val['args'][0] ) )
{
$func .= ' ';
$comma = '';
foreach( $val['args'] as $val )
{
$func .= $comma.print_var( $val );
$comma = ', ';
}
$func .= ' ';
}
$func .= ')';
}
echo "\n";
$indent .= "\t";
}
echo "</pre>\n";
}
trace( 'error outside function' );
function test( $param1, $param2, $param3, $param4 )
{
trace( 'error in test()' );
}
test( 1.1, "param2\n", array( 1 => "a\n", "b\n" => 2 ), false );
?>