问题
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-functions-closures-presentation)
"Object Orientation
- Lambda Functions are Closures because they automatically get bound to the scope of the class that they are created in.
- '
$this
' is not always needed in the scope.- Removing '
$this
' can save on memory.- You can block this behaviour by declaring the Lambda Function as static."
What is wrong with this code?
I get this error:
Parse error: parse error, expecting `T_PAAMAYIM_NEKUDOTAYIM' in C:\wamp\www\z-final\a.php on line 11
Why this code line doesn't work "return static function(){var_dump($this);};" ?
class foo
{
public function getLambda()
{
return function(){var_dump($this);};
}
public function getStaticLambda()
{
return static function(){var_dump($this);};
}
}
$foo = new foo();
$lambda = $foo->getLambda();
$staticLambda = $foo->getStaticLambda();
$lambda();
$staticLambda();
回答1:
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...
回答2:
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..."
来源:https://stackoverflow.com/questions/12579657/does-a-php-static-anonymous-function-really-work