Making your life easier during PHP debugging

Many times you need to debug some PHP variables and functions, especially when you need to troubleshoot some code written by someone else.

I know some developers use the function error_log here and there and try to understand which functions are called.

PHP gives us a very useful function: debug_backtrace, let’s use it to build this very simple but useful function that will make our life easier during the debugging.

 

//Error log function helper
function jose_error_log( $arg ){
    $trace = debug_backtrace();
    $trace1 = $trace[1];
    $trace = array_reverse( $trace );
    $output = '';
    foreach( $trace as $arr ){
        $output .= PHP_EOL.sprintf( 'Called function %s in file %s at line %s',$arr['function'],$arr['file'],$arr['line'] );
    }
    $output .= PHP_EOL.sprintf( '%s debugged at line %s in the function %s: %s',ucfirst( gettype( $arg ) ),$arr['line'],$trace1['function'],print_r( $arg,true ) );
    error_log( $output );
}

 

Let’s imagine you need to debug the variable $arg in the function example_function included in your-file.php.

 

function example_function( $arr ){

    $arg = example_another_function( $arr ); //example_another_function is included in file-example.php

    jose_error_log( $arg );

}

 

Using  jose_error_log( $arg ) you will find in wp-content/debug.php an output that looks like:

Called function example_another_function in file path_example\file-example.php at line 25
Called function example_function in file path_example\your-file.php at line 289
Called function jose_error_log in file path_example\your-file.php at line 1614
String debugged at line 1614 in the function example_function: 1241

 

It will be a lot easier to check which functions are involved and your life will be easier.

Of course, this method doesn’t want to replace more advanced debugging tools as Xdebug or similar, but many times you don’t need more than this.