I\'m trying to learn PHP, and now I\'m stuck in \'static anonymous function\'.
I found this in a tutorial (http://www.slideshare.net/melechi/php-53-part-2-lambda-fun
Yes, that is perfectly valid syntax in 5.4+.
Basically, it prevents auto-binding of the current class to the closure (in fact, it prevents all binding, but more on that later).
class Foo {
public function bar() {
return static function() { var_dump($this); };
}
public function baz() {
return function() { var_dump($this); };
}
}
If we instantiate that on 5.4+, the closure bar()
returns will have $this
set to null. Just as if you made a static call to it. But baz()
would have $this
set to the foo instance you called baz()
on.
So:
$bar = $f->bar();
$bar();
Results in:
Notice: Undefined variable: this in /in/Bpd3d on line 5
NULL
And
$baz = $f->baz();
$baz();
Results in
object(Foo)#1 (0) {
}
Make sense? Great.
Now, what happens if we take closures defined outside of a function:
$a = function() { var_dump($this); };
$a();
We get null
(and a notice)
$c = $a->bindTo(new StdClass());
$c();
We get StdClass
, just as you'd expect
$b = static function() { var_dump($this); };
$b();
We get null
(and a notice)
$d = $b->bindTo(new StdClass());
$d();
This is where things get interesting. Now, we get a warning, a notice, and null:
Warning: Cannot bind an instance to a static closure in /in/h63iF on line 12
Notice: Undefined variable: this in /in/h63iF on line 9
NULL
So in 5.4+, you can declare a static closure, which results in it never getting $this
bound to it, nor can you ever bind an object to it...
There should be no need to define it with the static
keyword.
<?php
class House
{
public function paint($color)
{
return function() use ($color) { return "Painting the house $color..."; };
}
}
$house = new House();
$callback = $house->paint('red');
var_dump($callback); // object(Closure)#2 (2) {..}
var_dump($callback()); // "Painting the house red..."