12

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!

1
  • Since PHP 5.6 you can use argument unpacking: new SomeClass( ... [ 'arg1', 'arg2' ] ); Commented Jul 24, 2017 at 9:40

2 Answers 2

20

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 );
Sign up to request clarification or add additional context in comments.

4 Comments

Another feature of PHP 5.3 I wasn't aware of. Thanks, it's gonna do it.
Thank you for the example. This is probably the first thing in the PHP manual that I've found wasn't explained very well.
@zneak, ReflectionClass::newInstanceArgs is not new in PHP 5.3, we've had it around since 2006 when it was released with PHP 5.1.3. @byronh, is there anything in particular that you found not well explained or are you referring to the parts labeled as "undocumented"? (Feel free to email me, [email protected])
@salathe: +1 exactly. That was what I was trying to bring across.
-2

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.

1 Comment

What is wrong with this answer? Any comments? Is it just because of eval? I've clearly stated at the beginning this is an alternative solution using eval

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.