将参数从php中的数组传递给构造函数

Agr*_*jag 32 php arrays constructor arguments function

通常,如果我想将$ myarray中的参数传递给$ somefunction,我可以在php中使用

call_user_func_array($somefunction, $myarray);
Run Code Online (Sandbox Code Playgroud)

但是,当希望调用的函数是对象的构造函数时,这不起作用.出于相当明显的原因,它无法做到:

$myobj = new call_user_func_array($classname, $myarray);
Run Code Online (Sandbox Code Playgroud)

有什么相当优雅的确有效吗?

Gor*_*don 65

您可以使用Reflection API:

例:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
Run Code Online (Sandbox Code Playgroud)

  • 在PHP 5.6中,您还可以通过``...``或splat运算符使用参数解包:http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat (10认同)