对象数组的内爆

时间:2016-08-08 16:16:26

标签: php silex array-map

我有一个简单的(我认为)。

我有一个Silex应用程序......我创建了一个服务services.yml文件,我的服务带有参数。对于coruse,参数可以是另一个类的实例:

services:
   Service:
      class: App\Services\xxxxxService
      arguments:
         - App\Lib\Parser\JsonParser
         - xxxxxx

所以,在我的init应用程序中,我有这段代码:

$services = $this['config']['services'];

    foreach ($services as $name => $service) {
        $className = $service['class'];

        $args = array_map(function ($arg) {
            if(class_exists($arg)){
                return new $arg;
            } else {
                return $arg;
            }
        }, $service['arguments']);
        $args = implode(',', $args);

        $this[$name] = new $className($this, $args);
    }

此代码给出了错误:

可捕获的致命错误:第252行的/ app/src/Application.php中无法将类App \ Lib \ Parser \ JsonParser的对象转换为字符串

我的目标是$ this [$ name] = new $ className($ this,$ args [0],$ args [1] ....),但我不能使用implode函数。

任何想法???

提前谢谢!!

微米。

1 个答案:

答案 0 :(得分:1)

我建议您使用ReflectionClass来实例化$className

收集完所有$args之后,请不要使用implode方法,因为它无法正确传递args到类构造函数。

所以$argsarray

array_unshift($args, $this); # Prepend $this in args
$refl = new ReflectionClass($className);
$this[$name] = $refl->newInstanceArgs($args); #Instatiate $className with appropriate args.
相关问题