简体   繁体   English

匿名函数中的 PHP 变量

[英]PHP variables in anonymous functions

I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them.我在 PHP 中玩弄匿名函数并意识到它们似乎无法访问它们之外的变量。 Is there any way to get around this problem?有没有办法解决这个问题?

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吗?

Yes, use a closure :是的,使用闭包

functionName($someArgument, function() use(&$variable) {
  $variable = "something";
});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & .请注意,为了能够修改$variable并在匿名函数的范围之外检索修改后的值,必须在闭包中使用&引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM