Wow, I can’t believe I missed this…nobody seems to be talking about it at all. Ever since PHP 5.3, I can finally do non-generic callbacks.
UPDATE: Check out this description of PHP lambdas (much better than what I’ve done in the following).
function do_something($value)
{
// used >= 2 times, but only in this function, so no need for a global
$local_function = function($value) { ... };
// use our wonderful anonymous function
$result = $local_function($value);
...
// and again
$result = $local_function($result);
return $result;
}
There’s also some other great stuff you can do:
$favorite_songs = array(
array('name' => 'hit me baby one more time', 'artist' => 'britney'),
array('name' => 'genie in a bottle', 'artist' => 'xtina'),
array('name' => 'last resort', 'artist' => 'papa roach')
);
$song_names = array_map(function($item) { return $item['name']; }, $favorite_songs);
GnArLy bra. If PHP was 20 miles behind Lisp, it just caught up by about 30 feet. This has wonderful implications because there are a lot of functions that take a callback, and the only way to use them was to define a global function and send in an array() callback. Terrible. Inexcusable. Vomit-inducing.
Not only can you now use anonymous functions for things like array_map() and preg_replace_callback(), you can define your own functions that take functions as arguments:
function do_something_binary($fn_success, $fn_failed)
{
$success = ...
if($success)
{
return $fn_success();
}
return $fn_failed();
}
do_something_binary(
function() { echo "I successfully fucked a goat!"; },
function() { echo "The goat got away..."; }
);
Sure, you could just return $success and call whichever function you need after that, but this is just a simple example. It can be very useful to encapsulate code and send it somewhere, this is just a demonstration of the beautiful new world that just opened for PHP.
So drop your crap shared host (unless it has >= 5.3.0), get a VPS, and start using this wonderful new feature.