Jump to content

Instantiate classes dynamically without conditionals


xaeryan

Recommended Posts

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

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.