zneak
zneak

Reputation: 138031

Call a constructor from variable arguments with PHP

I have a function that takes variadic arguments, that I obtain from func_get_args().

This function needs to call a constructor with those arguments. However, I don't know how to do it.

With call_user_func, you can call functions with an array of arguments, but how would you call a constructor from it? I can't just pass the array of arguments to it; it must believe I've called it "normally".

Thank you!

Upvotes: 12

Views: 4336

Answers (2)

DUzun
DUzun

Reputation: 1712

If for some reason you can not use ReflectionClass::newInstanceArgs here is another solution using eval():

function make_instance($class, $args) {
   $arglist = array();
   $i = 0; 
   foreach($args => &$v) {
       $arglist[] = $n = '_arg_'.$i++;
       $$n = &$v;
   }
   $arglist = '$'.implode(',$',$arglist);
   eval("\$obj = new $class($arglist);");
   return $obj;
}
$instance = make_instance('yourClassName', $yourArrayOfConstructorArguments);

Note that using this function enables you to pass arguments by reference to the constructor, which is not acceptable with ReflectionClass::newInstanceArgs.

Upvotes: -2

Decent Dabbler
Decent Dabbler

Reputation: 22773

For PHP < 5.3 it's not easily doable without first creating an instance of the class with call_user_func_array. However with Reflection this is pretty trivial:

$reflection = new ReflectionClass( 'yourClassName' );
$instance = $reflection->newInstanceArgs( $yourArrayOfConstructorArguments );

Upvotes: 20

Related Questions