我正在努力学习 PHP,但现在我陷入了“静态匿名函数”。
我在教程 ( 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."
这段代码有什么问题?
我收到这个错误:
Parse error: parse error, expecting `T_PAAMAYIM_NEKUDOTAYIM' in C:\wamp\www\z-final\a.php on line 11
为什么此代码行不起作用“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();
最佳答案
是的,这在 5.4+ 中是完全有效的语法。
基本上,它会阻止当前类自动绑定(bind)到闭包(事实上,它会阻止所有绑定(bind),但稍后会详细介绍)。
class Foo {
public function bar() {
return static function() { var_dump($this); };
}
public function baz() {
return function() { var_dump($this); };
}
}
如果我们在 5.4+ 上实例化它,闭包 bar()
返回会将 $this
设置为 null。就像您对它进行静态调用一样。但是 baz()
会将 $this
设置为您调用 baz()
的 foo 实例。
所以:
$bar = $f->bar();
$bar();
结果:
Notice: Undefined variable: this in /in/Bpd3d on line 5
NULL
和
$baz = $f->baz();
$baz();
结果
object(Foo)#1 (0) {
}
有道理吗?太好了。
现在,如果我们采用在函数外部定义的闭包会发生什么:
$a = function() { var_dump($this); };
$a();
我们得到 null
(和一个通知)
$c = $a->bindTo(new StdClass());
$c();
我们得到 StdClass
,正如您所期望的那样
$b = static function() { var_dump($this); };
$b();
我们得到 null
(和一个通知)
$d = $b->bindTo(new StdClass());
$d();
这就是事情变得有趣的地方。现在,我们收到警告、通知和 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
因此在 5.4+ 中,您可以声明一个静态闭包,这将导致它永远不会将 $this
绑定(bind)到它,也不能将对象绑定(bind)到它...
关于php - PHP 静态匿名函数真的有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12579657/