我怎么能用call_user_func_array调用类的构造函数
不可能这样做:
$obj = new $class();
call_user_func_array(array($obj, '__construct'), $args);
Run Code Online (Sandbox Code Playgroud)
因为如果构造函数有参数,则new将失败.
约束:我不控制我必须实例化的类,也不能修改它们.
不要问我为什么要做这个疯狂的事情,这是一个疯狂的考验.
我知道可以使用call_user_func_array()调用一个带有可变数量参数的函数 - > http://php.net/manual/en/function.call-user-func-array.php.我想要做的几乎是相同的,但我想要在它的构造函数中调用一个带有可变数量参数的PHP类,而不是函数.
它会像下面这样工作,但我不知道参数的数量,所以我不知道如何实例化该类.
Run Code Online (Sandbox Code Playgroud)<?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]);