views:

521

answers:

2

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

+8  A: 

Yep, definitely.

$className = 'MyClass';
$object = new $className;
brianreavis
Cool, I should've tested that before asking hehe. Thanks!
+1  A: 

Yes it is:

<?php

$type = 'cc';
$obj = new $type; // outputs "hi!"

class cc {
    function __construct() {
        echo 'hi!';
    }
}

?>
Mr. Smith