php匿名函数中的变量 [英] php variables in anonymous functions

查看:105
本文介绍了php匿名函数中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中使用匿名函数进行游戏,并意识到他们似乎没有达到他们之外的变量。
是否有办法解决这个问题?



示例:

  $ variable =nothing; 
$ b functionName(someArgument,function(){
$ variable =something;
});

echo $ variable;

输出:nothing。有没有什么办法可以让匿名函数访问$变量?

解析方案

是的, php.net/closure>使用闭包

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

请注意,为了您能够修改 $ variable 并在匿名函数范围外检索修改后的值,它必须使用& 来引用闭包。


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;

Will output: "nothing". Is there any way that the anonymous function can access the $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 &.

这篇关于php匿名函数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆