Bijou Trouvaille
Bijou Trouvaille

Reputation: 9424

In PHP 5 can I instantiate a class dynamically?

Is it possible to dynamically instantiate a class using a variable? For example is something like this possible in PHP?

class foo
{
    public $something;
}

$class_name = "foo";

$f = new $class_name();

Upvotes: 47

Views: 15832

Answers (4)

timdev
timdev

Reputation: 62874

Yes, this code will work fine.

Upvotes: 10

Muneer
Muneer

Reputation: 7564

Yes of course you can instantiate using dynamic names;

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382646

In PHP 5 can I instantiate a class dynamically?

Yes you can, your code should work fine.

Upvotes: 4

Chris Kloberdanz
Chris Kloberdanz

Reputation: 4536

That should work, yes.

You can also do:

$f = new $class($arg1,$arg2);

Upvotes: 45

Related Questions