xaeryan Posted February 22, 2009 Share Posted February 22, 2009 I have a database field that I am pulling which specifies what class name I'm using to instantiate an object. How can I create a new object based on the database field without hard coding the class name during instantiation. Let me give an example: $class_name = 'MyClass1'; // this will come from a database in my project $obj = new exec($class_name); // makes a MyClass1 object $obj->doSomething(); (all classes I'm using will have this method). I dont want to use conditionals, or anything like this: if ($class_name == 'MyClass1') $obj = new MyClass1 else if ($class_name == 'MyClass2') $obj = new MyClass2 Link to comment https://forums.phpfreaks.com/topic/146319-instantiate-classes-dynamically-without-conditionals/ Share on other sites More sharing options...
rhodesa Posted February 22, 2009 Share Posted February 22, 2009 you should just be able to do: $obj = new $class_name; Link to comment https://forums.phpfreaks.com/topic/146319-instantiate-classes-dynamically-without-conditionals/#findComment-768219 Share on other sites More sharing options...
xaeryan Posted February 22, 2009 Author Share Posted February 22, 2009 LOL, ok, that was easier than I expected. Sorry! Link to comment https://forums.phpfreaks.com/topic/146319-instantiate-classes-dynamically-without-conditionals/#findComment-768289 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.