Pass arguments from array in php to constructor [duplicate]

为君一笑 提交于 2019-12-17 22:38:34

问题


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

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:


You can use the Reflection API:

  • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.

Example:

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


来源:https://stackoverflow.com/questions/3395914/pass-arguments-from-array-in-php-to-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!