Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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 ?

share|improve this question

marked as duplicate by Gordon Apr 1 at 14:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 21 down vote accepted

You can use the Reflection API:

Example:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
share|improve this answer

Or, you could just pass the array directly?

$myObj = new $classname($myArray);

And read the elements of the array inside the method as if they are parameters to that method (the constructor in this case).

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.