我知道可以使用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