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
Found a possible duplicate of How to "invoke" a class instance in PHP? after answering it. – Gordon Aug 3 '10 at 11:29
feedback

2 Answers

up vote 13 down vote accepted

You can use the Reflection API:

Example:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
share|improve this answer
This seems like a good answer. Unfortunately, when I try it I get weird errors, ones I -don't- get when I do say: $foo = new Foo($arr[1],$arr[2]); I can't -really- do that though, because there's a variable and unknown amount of arguments in the array. – Agrajag Aug 3 '10 at 12:26
@Agrajag you pass in one array that contains all arguments – Gordon Aug 3 '10 at 12:48
Yes, that's precisely what I want to do -- and what call_user_func_array does. The problem is that I get an error about undefined call to CtCgiController() when I create a new object with the ReflectionClass whereas I don't get any problem when I create the very same object with new Classname(args...), this confuses me because my impression was that the two should be equivalent. – Agrajag Aug 4 '10 at 5:33
@Agrajag weird indeed. Can you give the exaxt error message please? – Gordon Aug 4 '10 at 6:34
The exact error is "Warning: Missing argument 1 for Module::Module() in /devel2/eivind/src/cp/cplib/Module.php on line 44", which is not really informative without the entire sourcecode. I'll investigate further, I guess it's possible that the ReflectionClass is merely somehow triggering an error that was really there all along. – Agrajag Aug 5 '10 at 6:07
feedback

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
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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