2011-01-30 94 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() 

?>