Reputation: 138031
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
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
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