Useful PHP functions for debugging

Useful PHP functions for debugging

Debug functions are useful because they allow you to output the values of variables in your program at certain points. There are two inbuilt PHP functions for this: print_r() and error_log(). Regardless of which system I work on, I always tend to use the same wrapper functions for debugging because they are easy to use and reduce the amount of typing …

Outputing debug messages to the PHP error log

function el($v, $l='DGB') { 
   error_log($l. ': '. print_r($v,1)); 
}
el(array(1,2,3), 'my debug message');

This will output an array or other variable to the error log in a nicely formatted output. The optional label is useful when outputing lots of error log messages so that you can easily tell which one is which.

Outputing debug messages to the screen

function pr($v, $l='DGB') { 
   print('<pre>'. $l. ': '); print_r($v); print('</pre>'); 
}
pr(array(1,2,3), 'my debug message');

This will output an array or other variable to the screen in a nicely formatted output thanks to the HTML pre tags. Again there is an optional label which can be used.

Easily switching debug messages on and off

If you wanted the ability to easily switch error messages on or off according to the level of debugging required, you could easily do this by setting a global debug level and adding another parameter to the debug functions. Taking the el() function as an example…

define(DEBUG_LEVEL,3);
function el($v, $n=2, $l='DGB') { 
   if($n>=DEBUG_LEVEL) error_log($l. ': '. print_r($v,1)); 
}
el(array(1,2,3), 3, 'my debug message');

In the above example, since the global debug is set to 3 and the el function defaults to 2, unless you pass in 3 or more the message will not be output. Normally I don’t bother with this approach and prefer to manually uncomment debug messages when I no longer am using them.

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>