Thursday, November 19, 2009

Simple effective PHP debugging + backtracking

During PHP debugging I often need to debug complex data. Is not always possibile to use Xdebug and the IDE debugging features with MVC frameworks, and also some arrays/object are too big and unhandy for FirePHP.

A valid solution might be a traditional "print_r"/"var_dump" + "exit"
Two problems:
1) accidental commits to the staging/production environment.
2) it takes time to understand where they are placed in the code, also because of the "exit".

Solutions:
Make a function to debug that
1) use a (external) constant (define) that define what is the environment and return without debugging and exiting if the environment is not the localhost one.
2) print the backtrace to easily find and remove the "breakpoints"

Code:

function pd($var, $useVarDump=false, $exit=true){

if (IS_PRODUCTION_ENV) return;
echo '<pre>';
if ($useVarDump) var_dump($var); else print_r($var);
echo "\n\nBACKTRACE:";
print_r(array_slice( debug_backtrace(false),1) ;
echo '</pre>';
if ($exit) exit;

}

No comments:

Post a Comment

 

PHP and tips|PHP