News for hackers. Stuff that matters.
Re:Functional PHP 5.3 - What are Anonymous Functions and Clo... by alexfarran on Tuesday August 18, 2009 @12:14PM (#770755)
It's on my list! If we're doing a feature comparison of web scripting languages it was obviously lacking from PHP and present in one form or another in everything else. Not sure about the use syntax but at least it makes it clear what variables are closed over.
Re:Functional PHP 5.3 - What are Anonymous Functions and Clo... by KrisJordan on Tuesday August 18, 2009 @12:25PM (#770781)
The use syntax is a little weird at first but it turns out to be straightforward to understand. In fact, being explicit about what is being closed over makes the function itself easier to understand.

PHP, being the quirky language that it is, needs the use syntax to enable closures for cases where there are dynamic variable references. This is a bad example but illustrates the problem:

$foo = 'bar'; $fun = function() use ($foo) { $var = 'foo'; echo ${$var}; }; $fun(); // output 'bar'

$fun = function() { $var = 'foo'; echo ${$var}; }; $fun(); // fails

Sure, you could close over the entire local namespace but that's an efficiency nightmare and leads to unpredictable code.