2017-03-09 14 views
0

我想調用一個類函數來創建一個子類的新實例。使用變量的名稱和參數在PHP中創建一個類的新實例

我這樣做是與子類名以下變量和參數的foreach循環中:

$classname = 'Element_Radio'; 
$classargs = array($a, $b); //Might have up to 4 arguments 

這裏的代碼我試圖執行原線,沒有任何的以上變量:

$form->addElement(new Element_Radio($required, $required, $optional_array, $optional_array); 

所以首先我想:

$form->addElement(new $classname ($classargs)); 

但我想我需要索姆ething這樣的:

$form->addElement(call_user_func_array(new $classname,$classargs)); 

無論哪種方式,我得到的錯誤:

「警告:缺少論據2元:: __結構()......」

所以它看起來像參數傳入一個數組變量,而不是分開。

我寫了一堆if語句,只是根據$classargs的值進行函數調用,但我想知道是否有編程方式做我想要的沒有IF的。

編輯 - 解決方案與我添加的代碼說明了我的參數數組是一個多維數組沒有所有數字索引的事實。 splat運算符(...)僅適用於具有數字索引的數組。

$classname = 'Element_Radio'; 
$classargs = array(); 

if (isset($a)) { array_push($classargs, $a); } 
if (isset($b)) { array_push($classargs, $b); } 
if (isset($c)) { array_push($classargs, $c); } 
if (isset($d)) { array_push($classargs, $d); } 

$form->addElement(new $classname (...$classargs)); 

回答

5

要麼使用​​:

new $classname(...$classargs) 

或者reflection

(new ReflectionClass($classname))->newInstanceArgs($classargs) 
+0

可變參數函數運算符是函數的定義,那就是爭論拆包或圖示 – AbraCadaver

+0

阿權。除了「...令牌」之外,似乎並沒有真正的官方名稱,這使得談論起來有點困難。 – deceze

+0

我最終使用上面編輯過的代碼,通過搜索來到這裏的任何人。 – Michelle

相關問題