PHP variables in anonymous functions

﹥>﹥吖頭↗ 提交于 2019-11-26 03:09:29

问题


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?

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?


回答1:


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 &.



来源:https://stackoverflow.com/questions/11420520/php-variables-in-anonymous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!