我在 PHP 中使用匿名函数并意识到它们似乎无法访问它们之外的变量。 有什么办法可以解决这个问题吗?
例子:
$variable = "nothing";
functionName($someArgument, function() {
$variable = "something";
});
echo $variable; //output: "nothing"
这将输出“无”。匿名函数有什么方法可以访问$variable
?
最佳答案
是的,use a closure :
functionName($someArgument, function() use(&$variable) {
$variable = "something";
});
请注意,为了让您能够修改 $variable
并在匿名函数范围之外检索修改后的值,必须在闭包中使用 &< 引用它
。
关于匿名函数中的 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420520/