PHP is now less crappy than Java

And by “is less crappy than Java”, I mean “has closures”.

The syntax goes thus:

function fun() {
    $a = 1;
    $b = 2;
 
    // variables being closed around need to be
    // explicitly specified:
    $closure = function() use($a) {
        // prints 1
        echo $a;
        // prints nothing (outer $b isn't in use)
        echo $b;
        // no effect outside $closure (outer $a not used as reference)
        ++$a;
    }
 
    //prints 1
    echo $a;
 
    $closure2 = function() use(&$a) { ++$a; }
    $closure2();
    // prints 2
    echo $a;
 
    // still prints 1 because $a was copied in the declaration
    // which is a bit of a wtf, but better than create_function
    $closure();
}

Now how long until PHP 5.3 is anything like widespread? I’m guessing three years or so.

Leave a Reply

You must be logged in to post a comment.