I've some code that creates ad instance with a dynamic class (i.e. from a variable):
$instance = new $myClass();
Since the constructor has different argument count depending on $myClass value, How do I pass a variable list of arguments to the new statement? Is it possible?
class Horse {
    public function __construct( $a, $b, $c ) {
        echo $a;
        echo $b;
        echo $c;
    }
}
$myClass = "Horse";
$refl = new ReflectionClass($myClass);
$instance = $refl->newInstanceArgs( array(
    "first", "second", "third"    
));
//"firstsecondthird" is echoed
You can also inspect the constructor in the above code:
$constructorRefl = $refl->getMethod( "__construct");
print_r( $constructorRefl->getParameters() );
/*
Array
(
    [0] => ReflectionParameter Object
        (
            [name] => a
        )
    [1] => ReflectionParameter Object
        (
            [name] => b
        )
    [2] => ReflectionParameter Object
        (
            [name] => c
        )
)
*/
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With