PHP 5.3!

Sat, 28 Mar 2009 13:12

Anonymous functions (and closures) are coming in 5.3! Seriously this is A BIG DEAL. in PHP 5.2 and earlier the only way to have an anonymous function is with the create_function() method. This method is nasty. Here's an example:

function do_stuff(callback) {
    /* do stuff */
    call_user_func(callback);
}
do_stuff(create_function("echo 'callback complete';"));

So you have code as a string. Not so great. Here's the only way to really do that:

function do_stuff(callback) {
    /* do stuff */
    call_user_func(callback);
}
function do_stuff_callback() {
    echo 'callback complete';
}
do_stuff('do_stuff_callback');

You see? I had to declare the callback method as a regular function and then pass its name is as a string... blegh! From PHP 5.3 onward things will look like this:

function do_stuff(callback) {
    /* do stuff */
    callback();
}

do_stuff (function () {
    echo 'callback complete';
});

So much cleaner! And if you've been writing serious javascript code recently (like me) you're going to feel right at home. (Except for the whole dollar variable prefix thing. What's with that?)

Here's some more information:
http://www.slideshare.net/sebastian_bergmann/of-lambda-functions-closures-and-traits