PHP: The Good* Parts Ep 1

 

Many of the things PHP gets berated for are simply misunderstood features of the language. The cause of this misunderstanding is undoubtedly the "fault" of the languages low barrier to entry. If I may steal a quote from Douglas Crockford, people are writing before learning the language. So instead of highlighting the "good parts" of the language I'm going to take a quick look at the pseudo-gotchas of PHP (I say pseudo-gotchas because they aren't gotchas, they are legitimate features that people abuse to no end).

The first I'll go over is one of the few that can actually be considered a true gotcha.

Variable Variables: Creates a variable from the value of a variable, ie., Plain<?php $hello = 'world'; $world = 'hello'; echo $$hello . ' ' . $hello; // hello world ?>

The gotcha can be seen in the following code: Plain<?php $vowels = array('a','e','i','o','u'); $vowel_count = count($vowels); for($i = 0; $i < $vowel_count; $i++) { #,-- bug (feature) $$vowels[$i] = $vowels[$i] . '_' . $i; // whoops } ?>

I'll give you a minute to figure out why that's an infinite loop. It's OK, I'll wait. Figured it out yet? As the array ($vowels) contains the key 'i' once $i == 2, the expression $$vowels[$i] = $vowels... really says $i = $vowels.... This is obviously not what was intended and sends it into an infinite loop.

While this is, indeed, a feature of the language albeit an esoteric and mostly unnecessary one it is usually harped on because most of the errors are filed PEBKAC.