gpt4 book ai didi

匿名函数中的 PHP 变量

转载 作者:IT老高 更新时间:2023-10-28 11:50:56 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com