从php数组传递参数到构造函数[复制]

时间:2022-10-16 12:38:59

This question already has an answer here:

这个问题已经有了答案:

Normally, if I want to pass arguments from $myarray to $somefunction I can do this in php using

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

call_user_func_array($somefunction, $myarray);

However this does not work when the function one wishes to call is the constructor for an object. For fairly obvious reasons it does not work to do:

然而,当你想要调用的函数是对象的构造函数时,这种方法就不起作用了。由于相当明显的原因,它不起作用:

$myobj = new call_user_func_array($classname, $myarray);

is there something fairly elegant that does work ?

有什么东西是相当优雅的吗?

1 个解决方案

#1


56  

You can use the Reflection API:

您可以使用反射API:

  • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.
  • 反射类::newInstanceArgs -从给定的参数创建一个新的类实例。

Example:

例子:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));

#1


56  

You can use the Reflection API:

您可以使用反射API:

  • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.
  • 反射类::newInstanceArgs -从给定的参数创建一个新的类实例。

Example:

例子:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));