Thursday, November 22, 2007

Using "IF Comments" in PHP

Here's a nifty hack using comments to quickly enable/disable a block of code. I haven't seen examples of this before so I feel special. Here we go.

Teh Test
Suppose you have the following code:
$data = get_crap();

echo "Debug:"
print_r($data);
I store some data to $data and as a debug I want to view the contents of $data. I want to disabled the debug quickly. This is going to look weird at first but I will explain.

Example Code:
$data = get_crap();

///*
echo "Debug:"
print_r($data);
//*/
///* is a valid comment. it starts with //. php ignores the /*
The echo and print_r work because only the line above was commented.
//*/ is a valid comment. it starts with //. php ignores the */

To disable execution of code:
(Remove the very first set of //'s)
$data = get_crap();

/*
echo "Debug:"
print_r($data);
//*/
/* is a multi-line block comment. php ignores everything until it finds a matching */
The echo and print_r are not seen by the compiler.
//*/ was ignored. Execution resumes after the */

Wait a second...
Why not just do this: ?
$data = get_crap();

/*
echo "Debug:"
print_r($data);
*/
Why not just use /* */ why /* //*/ ??

Beacuse! if you remove the first /* to 'uncomment' without removing the */ (an extra step by the way) you get this:
$data = get_crap();


echo "Debug:"
print_r($data);
*/
And this:

Parse error: parse error in c:\www\project\file.php on line n

meh, l8r

No comments: