Can PHP instantiate an object from the name of the class as a string?

Viewed 37372

Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string?

5 Answers

if your class need arguments you should do this:

class Foo 
{
   public function __construct($bar)
   {
      echo $bar; 
   }
}

$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
Related