gpt4 book ai didi

PHP 将变量传递给 array_walk_recursive

转载 作者:行者123 更新时间:2023-12-02 17:48:38 25 4
gpt4 key购买 nike

此代码有效,但 $vars 无法在 call() 函数中定义。为什么 $vars 不能传递给 array_walk_recursive()

class lib{

private $library;

function __construct($lib="")
{
$this->library = $lib;
}
function set($vars)
{
$decoded_classes = json_decode($this->library,true);
array_walk_recursive($decoded_classes,function(&$f) {$f = create_function($vars,$f);});
return $decoded_classes;
}
}
$json = '
{
"class1": {
"function1":"return \"$a<b>$b</b>!\";"
},
"class2": {
"function2":"return $b;",
"function3":"return $c;"
},
"function1":"return \"test\";"
}';
$lib = new lib($json);
$lib = $lib->set("$a,$b");
$lib = $lib["class1"]["function1"]("asdasasd","asdasasd");
echo $lib;

最佳答案

首先,看看this example with variable scoping for closures .您需要使用 use 关键字传递变量,例如:

array_walk_recursive($decoded_classes,function(&$f) use ($vars) {$f = create_function($vars,$f);});

如果您为我们定义了 $a$b 等就好了,这样我们就可以实际测试您的代码。

关于PHP 将变量传递给 array_walk_recursive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11386213/

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