php 5.3: notes about closures and lambda functions
Friday, July 18th, 2008Few days ago a friend of mine told me that php will support closures and lambda functions.
You can find example code and explanation about lambda functions and closures in php’s wiki
I just want to drop a few notes.
1. there are (still) no lambda classes, but I hope in next releases they will be implemented.
2. lambda function definitions must end with “;”. I think it’s important because I made a parse error first time ![]()
3. “By default, all imported variables are copied as values into the closure. This makes it impossible for a closure to modify the variable in the parent scope. By prepending an & in front of the variable name in the use declaration, the variable is imported as a reference instead. In that case, changes to the variable inside the closure will affect the outside scope.”
Well this is actually not correct. Objects are passed by reference. If you need to use objects in closures you still have to use clone.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class foo { public $bar = 5; } $foo = new foo; $lambda = function() use ($foo) { echo "Imported variable:".$foo->bar."\n"; $foo->bar++; }; $lambda(); echo "Original variable: ".$foo->bar."\n"; ?> |
result is:
Imported variable:5
Original variable: 6
4. closures combined with Reflection allow calling private method of a given object.
1 2 3 4 5 6 7 8 9 10 11 | <?php class Foo { private static function bar() { echo "I'm private method\n"; } } $class = new ReflectionClass('Foo'); $method = $class->getMethod('bar'); $closure = $method->getClosure(); $closure(); ?> |
Output is:
I’m private method