Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dynamic class instance programmatically in PHP with variable arguments?

Tags:

oop

php

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?

like image 269
Cranio Avatar asked Aug 09 '12 13:08

Cranio


1 Answers

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
        )

)
*/
like image 55
Esailija Avatar answered Oct 20 '22 10:10

Esailija