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

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

问题描述

我在 PHP 中玩弄匿名函数并意识到它们似乎无法访问它们之外的变量.有什么办法可以解决这个问题吗?

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?

示例:

$variable = "nothing";

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

echo $variable;  //output: "nothing"

这将输出无".匿名函数有没有办法访问$variable?

This will output "nothing". Is there any way that the anonymous function can access the $variable?

推荐答案

是的,使用闭包::>

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

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

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天全站免登陆