我有一个工厂类,如下所示:
class AisisCore_Factory_Pattern {
protected static $_class_instance;
protected static $_dependencies;
public static function get_instance(){
if(self::$_class_instance == null){
$_class_instance = new self();
}
return self::$_class_instance;
}
public static function create($class){
if(empty($class)){
throw new AisisCore_Exceptions_Exception('Class cannot be empty.');
}
if(!isset(self::$_dependencies)){
throw new AisisCore_Exceptions_Exception('There is no dependencies array created.
Please create one and register it.');
}
if(!isset(self::$_dependencies[$class])){
throw new AisisCore_Exceptions_Exception('This class does not exist in the dependecies array!');
}
if(isset(self::$_dependencies[$class]['params'])){
$new_class = new $class(implode(', ', self::$_dependencies[$class]['params']));
return $new_class;
}else{
$new_class = new $class();
return $new_class;
}
}
public static function register_dependencies($array){
self::$_dependencies = $array;
}
}现在,通过这个类,我们做了以下工作:
首先设置我们的类列表及其依赖项
$class_list = array(
'class_name_here' => array(
'params' => array(
'cat'
)
)
);注册它们:
AisisCore_Factory_Pattern::register_dependencies($class_list);这意味着,每当您调用create方法并传递给它一个类时,我们都将返回该类的一个新实例,同时还会传递该类的任何参数。
创建一个Clas
要创建一个类,我们所做的就是:
$object = AisisCore_Factory_Pattern::register_dependencies('class_name_here');现在我们已经创建了一个类的新实例:class_name_here并将它作为cat的参数,现在我们要访问它的方法就是do $object->method()。
我的问题是:
如果参数是数组呢?我该怎么处理呢?
一种解决办法可以是:
public static function create($class){
if(isset(self::$_dependencies[$class]['params'])){
if(is_array(self::$_dependencies[$class]['params'])){
$ref = new ReflectionClass($class);
return $ref->newInstanceArgs(self::$_dependencies[$class]['params']);
}
$new_class = new $class(implode(', ', self::$_dependencies[$class]['params']));
return $new_class;
}else{
$new_class = new $class();
return $new_class;
}
}发布于 2013-02-19 19:40:10
在这种情况下,最好的选择是可能使用反射类来创建传递参数数组的新实例。请参见反射类::newinstanceargs,并且用户注释具有类似的内容:
$ref = new ReflectionClass($class);
return $ref->newInstanceArgs(self::$_dependencies[$class]['params']);这应该像数组一样工作,因为数组中的每个值都作为不同的参数传递给函数。
https://stackoverflow.com/questions/14965633
复制相似问题