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 ?

Agrajag
  • 1,016
  • 2
  • 9
  • 24

1 Answers1

67

You can use the Reflection API:

Example:

$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstanceArgs(array('foo', 'bar'));
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 13
    In PHP 5.6 you can also use argument unpacking via the ``...`` or splat operator : http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat – jhuet Jun 13 '15 at 12:28
  • 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. – Shaun Cockerill Mar 26 '18 at 05:55