我知道可以使用call_user_func_array()調用具有可變數量參數的函數 - >http://php.net/manual/en/function.call-user-func-array.php。我想要做的事情幾乎完全相同,但是我不想調用一個函數,而是在構造函數中調用一個具有可變數量參數的PHP類。在構造函數中動態調用具有可變參數數量的類
它會像下面的工作,但我不知道參數的數量,所以我不會知道如何實例化類。
<?php //The class name will be pulled dynamically from another source $myClass = '\Some\Dynamically\Generated\Class'; //The parameters will also be pulled from another source, for simplicity I //have used two parameters. There could be 0, 1, 2, N, ... parameters $myParameters = array ('dynamicparam1', 'dynamicparam2'); //The instantiated class needs to be called with 0, 1, 2, N, ... parameters //not just two parameters. $myClassInstance = new $myClass($myParameters[0], $myParameters[1]);
你的問題有點模棱兩可。這聽起來像是你說現在你不知道構造函數會帶來多少個參數,但是它的數量會在運行時被修復,並且你想用正確的數字來調用它。那是對的嗎? – 2012-01-04 22:00:25
@jburbage是...要實例化的類的名稱以及構造函數的參數將被定義。我從另一個來源獲取這些信息。爲了簡單起見,我將其從此代碼中刪除。我要評論上面的代碼來澄清。 – bmarti44 2012-01-04 22:06:07
你見過[這個問題](http://stackoverflow.com/questions/1569949/instantiating-a-new-php-class-with-one-or-many-arguments)?那裏的答案可能會解決你的問題。 – 2012-01-04 22:07:04