21st Jan 2006

Posted in

Blog :: PHP bon mots

I have a few PHP witticisms to throw at you of varying value.  How about:
if (count(debug_backtrace()) == 0)
#do something

This is essentially the same trick as the if __name__ == "__main__" bit in python. Essentially it's code that runs if the file is being executed directly but not if it's being used as a library (ie imported or required in another file). The python one is ugly (I'm not a fan of the aesthetics of double underscore special vars in python), but at least it's a deliberate feature. The PHP version is a hack in the best sense of the word. I first saw this one on Harry Fuecks blog and have been using it since. Very useful just to put a few sanity checks in code this way.

Or how about this one: instead of writing the usual if($var == true) try writing if(true == $var). The benefit to this is that if($var =

true) is perfectly valid PHP code, but it's probably not what you want. Assignment to a constant, on the other hand, throws a compiler error. I haven't made up my mind about this idiom; putting the expected value first seems backwards to me.

In the same vein, did you know that array declarations in PHP can use commas as item terminators, not just separators. Therfore the following is perfectly valid.

$a = array('var1'=>'Value 1',
           'var2'=>'Value 2',

The benefit? Well, you'll probably add an additional line to the array at some point and if you didn't terminate with a comma, you'll probably miss adding it with the new line. I actually like this one and have been trying to use it (I think I saw this on Simon Willison's blog sometime.)

Finally, how about leaving the terminating ?> off of php files? This has the advantage of never ever leaving you with a frustrating hour spent debugging the cause of "output already started" errors resulting from whitespace after the terminating tag...

Got an opinion on the value of hacks like this? Syntactic sugar? Or rearranging the deck chairs on the Titanic. It's hard to tell sometimes...

Posted on Jan 21st 2006, 11:11 PM