此代码有效,但无法在$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;
答案 0 :(得分:5)
首先,看看this example with variable scoping for closures。您需要使用use
关键字传递变量,例如:
array_walk_recursive($decoded_classes,function(&$f) use ($vars) {$f = create_function($vars,$f);});
如果您为我们定义$a
,$b
等,那将是一件好事,因此我们实际上可以测试您的代码。