tags:

views:

287

answers:

3

Languages like C and even C# (which technically doesn't have a preprocessor) allow you to write code like:

#DEFINE DEBUG
...

string returnedStr = this.SomeFoo();
#if DEBUG
    Debug.WriteLine("returned string =" + returnedStr);
#endif

This is something I like to use in my code as a form of scaffolding, and I'm wondering if PHP has something like this. I'm sure I can emulate this with variables, but I imagine the fact that PHP is interpreted in most cases will not make it easy to strip/remove the debugging code (since its not needed) automatically when executing it.

+4  A: 

PHP doesn't have anything like this. but you could definitely whip up something quickly (and perhaps a regex parse to strip it out later if you wanted). i'd do it as such:

define('DEBUG', true);
...
if (DEBUG):
  $debug->writeLine("stuff");
endif;

of course you'd have to write your own debug module to handle all that. if you wanted to make life easier on regex parsing, perhaps you could use a ternary operator instead:

$str = 'string';
DEBUG ? $debug->writeLine("stuff is ".$str) : null;

which would make removing debug lines pretty trivial.

Owen
If you go this route, remember not to simple delete the define line. You need to define it as false to turn off the debugging, otherwise you'll get a stack of bareword warnings.
Matthew Scharley
A: 

It has a define funciton, documented here: http://us.php.net/manual/en/language.constants.php.

Given the set of differences between variables and constants explained in the documentation, I assume that PHP's define allows the interpreter to eliminate unusable code paths at compile time, but that's just a guess.

-- Douglas Hunter

douglashunter
+1  A: 

xdump is one of my personal favorites for debugging.

http://freshmeat.net/projects/xdump/

define(DEBUG, true);

[...]

if(DEBUG) echo xdump::dump($debugOut);
Jayrox