views:

130

answers:

2

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 ?

+6  A: 

You can use the Reflection API:

Example:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
Gordon
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
@Agrajag you pass in **one** array that contains **all** arguments
Gordon
@Gordon: 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
@Agrajag weird indeed. Can you give the exaxt error message please?
Gordon
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
+1  A: 

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).

w3d