PHP将变量传递给array_walk_recursive

时间:2012-07-08 20:00:33

标签: php arrays recursion

此代码有效,但无法在$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;

1 个答案:

答案 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等,那将是一件好事,因此我们实际上可以测试您的代码。