Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments from array in php to constructor [duplicate]

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 ?

like image 564
Agrajag Avatar asked Aug 03 '10 11:08

Agrajag


1 Answers

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')); 
like image 50
Gordon Avatar answered Oct 11 '22 06:10

Gordon