pistacchio
pistacchio

Reputation: 58883

Php dynamic class construction

I'm trying to avoid the use of eval. I can dynamically instantiate a class like this:

class myclass {}

$my_class_name = 'myclass';
$obj = new $myclass();

If the constructor is like follows:

class myclass {
    public function __construct( $argument1, $argument2 ) {}
}

and i have the values of the arguments in an array, how can i dynamically instantiate the class and pass it dynamic arguments? Mind that I have no way to modify the class, so I have to work on the way of using it.

Thanks

Upvotes: 5

Views: 3393

Answers (2)

Kamal Khan
Kamal Khan

Reputation: 97

$obj = new $myclass($array['key1'], $Arr['key2'], ...);

Upvotes: -2

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

ReflectionClass::newInstanceArgs seems to be just the thing you're looking for.

Upvotes: 7

Related Questions