Skip to main content


Showing posts from March, 2009

Goto and Exceptions

It slipped quietly under the radar for some. For others, it raised quite a stir. No, I'm not talking about PHP's implementation of namespaces (a battle that's finally done and over much to everyone's relief). I'm referring to the infamous goto statement.

Many programmers have had the "goto is evil" mantra drilled into them from an early start. The basis of this can probably be traced back to Edsger Dijkstra's March 1968 letter to the editor in Communications of the ACM (though he wasn't the first to argue against goto). Dijkstra felt the proliferation of goto at the time was producing unmaintainable "spaghetti" code. Fast-forward more than 40 years later and the controversial feature is still alive and well... and about to make its debut appearance in PHP.

I found myself discussing some of the new features in PHP 5.3 with a friend a few days ago after he read my previous post about anonymous functions and closures. Our conversation eventua…

Anonymous Functions and Closures

Of all the new goodies that are promised in PHP 5.3, the two which I think I am the most excited about are anonymous functions and closures.

Anonymous functions are functions that are defined without being bound to a proper name. Typically, anonymous functions are used only a limited number of times and for a specific purpose; you could think of them as "throw-away" functions if you'd like.

Let's consider the following example which illustrates a standard function used as a callback:
function percentVowels_callback($word) {
$word = strtolower($word);
$chars = count_chars($word);
$numVowels = 0;
foreach (array("a", "e", "i", "o", "u") as $vowel) {
$numVowels += $chars[ord($vowel)];
return $numVowels / strlen($word);

$animals = array("aardvark", "elephant", "iguana", "orangutan",
$percentVowels = array_map("percentVowels_callback…