2011-01-30 69 views
2

我想实现一个命令模式样式队列,我不知道如何将参数传递给对象的构造函数。如何使用'函数处理'样式函数实例化类?

我“的命令”图案存储在一个数据库中的对象,其中,我有一个表queue_items存储我的“的命令”的目的,与classmethodconstructor_arguments(存储为索引数组),method_arguments(作为存储的字段索引数组)和object_type(它是enum{'instance','static})。

如果object_type是'实例',我使用'new'关键字实例化对象。如果object_type是'静态',那么我只是使用forward_static_call_array()拨打电话。

如果我没有构造函数参数,我可以只使用这样的事情:

$instance = new $class_name(); //NOTE: no arguments in the constructor 
$result = call_user_func_array(array($instance, $method_name), $method_arguments); 

,如果我想从constructor_arguments的值传递到__construct(),我无法找到一个函数让我这样做。

我希望保留索引数组,而不是依赖专门的构造函数,这样我就不必重写我自己的和第三方类,我用它来处理,例如,将关联数组作为唯一参数一个构造函数。

有谁知道如何以call_user_func_array()的方式直接将索引数组传递给__construct?或者它可以不完成?

德鲁J.索内。

回答

2

可以使用ReflectionClass对于这种特殊情况:

$rc = new ReflectionClass($className); 
$instance = $rc->newInstanceArgs($array_of_parameters); 
+0

唉唉该死......甚至从来没有穿过我的脑海。谢谢! – Drew 2011-01-30 02:55:40

1

一个使用ReflectionClass更精细的例子:

<?php 
class MyClass 
{ 
    private $arg1; 
    private $arg2; 

    public function __construct($arg1, $arg2 = "Hello World") 
    { 
     $this->arg1 = $arg1; 
     $this->arg2 = $arg2; 
    } 

    public function print(){ 
     echo $this->arg2 . "," .$this->arg2; 
    } 
} 

$class = new ReflectionClass('MyClass'); 
$args = array(3,"outro"); 
$instance = $class->newInstanceArgs($args); 
$instance->print() 

?>