32

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 ?

0

1 Answer 1

67

You can use the Reflection API:

Example:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
Sign up to request clarification or add additional context in comments.

2 Comments

In PHP 5.6 you can also use argument unpacking via the ... or splat operator : php.net/manual/en/…
Quick and easy! I was already using the Reflection API in my new package loader module, and this gives me a way to account for any number of arguments in future versions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.