匿名函数中的 PHP 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11420520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP variables in anonymous functions
提问by einord
I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them. Is there any way to get around this problem?
我在 PHP 中玩弄匿名函数并意识到它们似乎无法访问它们之外的变量。有没有办法解决这个问题?
Example:
例子:
$variable = "nothing";
functionName($someArgument, function() {
$variable = "something";
});
echo $variable; //output: "nothing"
This will output "nothing". Is there any way that the anonymous function can access the $variable?
这将输出“无”。有什么方法可以让匿名函数访问$variable?
回答by nickb
Yes, use a closure:
是的,使用闭包:
functionName($someArgument, function() use(&$variable) {
$variable = "something";
});
Note that in order for you to be able to modify $variableand retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &.
请注意,为了能够$variable在匿名函数的范围之外修改和检索修改后的值,必须在闭包中使用&.

