Reputation: 864
I'm wondering how one creates a debug room for their applications.
My example is that I output variable content to the screen for me to have a visual on what my variables are doing throughout the process. To make sure they are doing what they should be doing. (poor man's tdd?)
--------NEW CODE--------------------
So this is what I came up with for now but it involves a !!global variable!!
I have a common file that is included with all the pages of my script. In there I put the following:
<?php //COMMON FILE
$debug_mode = 'on'; //my trigger
if( strtolower($debug_mode) == 'on'){
$debug = "<hr /><pre>";
if( file_exists('debug_mode.php') ){ //This file will never be used in a
include('debug_mode.php'); //a production environment
}
}
function debug($str, &$debug){
if( function_exists('debugff') ){
$str = debugff($str, $debug);
}
else{
unset($debug);
}
}
?>
.
<?php //DEBUG_MODE FILE NEVER USED IN PRODUCTION MODE
if( strtolower($debug_mode) == 'on'){
function debugff($debugstring, &$debug){
global $debug;
if( is_null($debugstring) ){
echo $debug . "</pre><hr />";
}
else{
$debug .= $debugstring . "\n";
}
}
}
?>
To use the script I use a call to the debug function.
debug("username:$user", $debug);
And I can do that a million times. and when I want to print the results I simply call
debug(null, $debug);
I've heard countless number of times to never use a global variable and this is the first time I implement it. Granted the way I have it set up would mean that in the 'real world' the global variable will never get called, but how would I get the global variable out of here.
Upvotes: 0
Views: 810
Reputation: 197787
Instead of using a global variable you can just call the function (on a single line each).
Then create a build-script that is compiling (as this is PHP read: putting together) the production code. That build script just removes all lines containing those invocations.
The build script also does not copy the definition of the function.
Then run the acceptance and integration tests on the production code for the build. As the definition off the debug function is now missing, it would trigger a fatal error when called. Those fatal errors would be noticed by the integration and acceptance tests. But because all invocations have been stripped, the tests should pass w/o any problem.
Upvotes: 0
Reputation: 5626
Try to learn a PHP framework. They solve these problems better and in an OOP way.
Anyway, in your example, you can remove a lot of the code:
$debug_mode = TRUE;
function dump() {
global $debug_mode;
if ($debug_mode) {
call_user_func_array('var_dump', func_get_args());
}
}
You can then dump your variables with dump($var1, $var2, $var3) and don't worry about the production mode outside this function. The dumps will not be showed once you trigger the debug mode off.
Upvotes: 1