PHP 闭包是否损坏或者我遗漏了什么?
我一直在阅读 PHP 5.3 的新功能,其中主要功能之一是闭包。
除非我犯了严重错误,否则 PHP 开发人员要么是:
a) 混淆闭包与匿名函数
b) PHP 5.3.1 中的闭包被破坏,我正在测试
wikipedia 所说的内容 闭包是匿名函数加上函数父级作用域变量与函数作用域的绑定的机制。最后一部分在 PHP 中似乎被破坏了。
我检查过 PHP 错误,但奇怪的是,没有发现任何相关内容。
这是我的测试方式:
<?php
function getFun() {
$x = 2;
return function() {
return $x;
};
}
$f = getFun(); // getFun()(); doesn't work -.-
var_dump($f()); // $f() == null
在实际实现闭包的语言中,它返回 2:
def f():
x = 2
return lambda: x
print(f()()) # prints 2
那么
alert((function() {
var x = 2;
return function() {
return x;
};
})()()); // alerts 2
,我错了吗?
I've been reading on the new features of PHP 5.3, and one of the major features are closures.
Unless I'm very badly mistaken, the PHP developers are either:
a) confusing closures with just anonymous functions
b) the closures are broken in PHP 5.3.1 in which I'm testing
From what wikipedia says closures are the mechanism of anonymous functions plus the binding of the function's parent's scope variables to the function's scope. The last part seems broken in PHP.
I've checked PHP bugs, and found nothing about this, strangely.
Here's how I'm testing:
<?php
function getFun() {
$x = 2;
return function() {
return $x;
};
}
$f = getFun(); // getFun()(); doesn't work -.-
var_dump($f()); // $f() == null
In languages that actually implement closures, it returns 2:
def f():
x = 2
return lambda: x
print(f()()) # prints 2
and
alert((function() {
var x = 2;
return function() {
return x;
};
})()()); // alerts 2
So, am I wrong or?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您习惯使用 JavaScript,PHP 的闭包实现与您可能期望的稍有不同。只需调用
function () { return x; }
不起作用,因为您必须利用use
语句。PHP's implementation of closures is slightly different from what you might expect if you're used to using JavaScript. Simply calling
function () { return x; }
won't work as you must take advantage of theuse
statement.从外部作用域继承的变量需要显式列出。从手册:
variables inherited from the outer scope need to be listed explicitely. from the manual: