In PHP 5 can I instantiate a class dynamically?

Bijou Trouvaille picture Bijou Trouvaille · Jun 24, 2010 · Viewed 15.1k times · Source

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();

Answer

Chris Kloberdanz picture Chris Kloberdanz · Jun 24, 2010

That should work, yes.

You can also do:

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