PHP 闭包无法访问父函数参数吗?
我一直在为 PHP 5.3 编写一些代码,我想做一些类似于下面显示的代码的事情。我希望这段代码打印“hellohello”,但它却打印“hello”,并且出现错误。
看起来 $inner 闭包无法访问外部函数的参数。这是正常行为吗?这是 PHP 的错误吗?我不明白这怎么能被认为是正确的行为......
<?php
function outer($var) {
print $var;
$inner = function() {
print $var;
};
$inner();
}
outer('hello');
谢谢!
I've been writing some code for PHP 5.3, and I wanted to do something similar to the code I'm showing below. I expect this code to print 'hellohello', but it prints 'hello' instead, and an error.
It appears the $inner closure does not have access to the outer function's parameters. Is this normal behavior? Is it a PHP bug? I can't see how that could be considered correct behavior...
<?php
function outer($var) {
print $var;
$inner = function() {
print $var;
};
$inner();
}
outer('hello');
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
use
关键字。有关更多详细信息,请参阅此。维基百科对此有一些解释:
因此,为了使您的示例按照您希望的方式工作:
You need to use the
use
keyword. See this for more details.Wikipedia has some explanation of this:
So, to make your example work the way you want it to:
我猜测 $inner 函数没有访问 $var
尝试这个的 范围
I would guess that the $inner function doesn't have the scope to access $var
Try this