views:

168

answers:

1

Hello guys,

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!

+8  A: 

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 );
fireeyedboy
Another feature of PHP 5.3 I wasn't aware of. Thanks, it's gonna do it.
zneak
Thank you for the example. This is probably the first thing in the PHP manual that I've found wasn't explained very well.
Lotus Notes
@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
@salathe: +1 exactly. That was what I was trying to bring across.
fireeyedboy