0

我有这样的工厂模式:

public function ViewFactory implements Factory {
    public function __construct() {

    }

    public static function Create($params) {
        //does not return variables, only extracts them
        $p = extract($params, EXTR_PREFIX_ALL, "var_");

        //return object of view and pass in all variables extracted from array
        return new View($p);
    }

    ***
    ***
}

interface Factory {
   public function Create($params);
   ***
   ***
}

我试图使用extract但它不返回变量我只需要使用以var_为前缀的关联数组中的键来访问它们。是否有可能以某种方式将数组的所有值作为逗号分隔的变量返回并将其传递给函数?

我的视图类:

class View {
   public function __construct($path, $parameters, $site_title) {
         ***
   };
} 
4

2 回答 2

2

我不太确定这是否是您所要求的,但您可以使用ReflectionClass::newInstanceArgs创建一个类的实例并从数组传递它的参数:

public static function Create($params) {
    $class = new ReflectionClass('View');
    return $class->newInstanceArgs($params);
}
于 2013-07-12T19:30:58.797 回答
1

您可以像这样将它们三个传递给视图:

// This will reset the keys in the array, so the keys will now be [0] [1] and [2]
$p = array_values($p);

// Pass the values one by one
return new View($p[0], $p[1], $p[2]);
于 2013-07-12T19:31:12.767 回答