Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 671
Bijou Trouvaille Avatar asked Jun 24 '10 18:06

Bijou Trouvaille


3 Answers

That should work, yes.

You can also do:

$f = new $class($arg1,$arg2); 
like image 174
Chris Kloberdanz Avatar answered Oct 06 '22 00:10

Chris Kloberdanz


Yes, this code will work fine.

like image 34
timdev Avatar answered Oct 05 '22 22:10

timdev


In PHP 5 can I instantiate a class dynamically?

Yes you can, your code should work fine.

like image 30
Sarfraz Avatar answered Oct 05 '22 23:10

Sarfraz