Forum Moderators: coopster
I have a database table, for sake of simplicity lets say it's a table of categories which is filled with the following data: Dog, Cat, Mouse and Sheep. The app has an abstract class Animal and 4 child classes which extend it; Dog, Cat, Mouse and Sheep. The parent and child classes all have the same constructor parameters. The script then reads each category from the database and instantiates the child class based on the category name.
eg: (pseudocode)
read categories from database
foreach category {
if category = Dog, return new Dog('arg1', 'arg2', 'arg3', etc)
if category = Cat, return new Cat('arg1', 'arg2', 'arg3', etc)
if category = Mouse, return new Mouse('arg1', 'arg2', 'arg3', etc)
if category = Sheep, return new Sheep('arg1', 'arg2', 'arg3', etc)
...etc, etc
}
What would be the simplest and best way to instantiate the child classes based on the category name?
I've tested a switch statement, but it looks stupid and repetitive since their are 10+- categories an therefore 10+- child classes. I've also tried php's newish reflection methods, but this feels a bit erky.
any suggestions?
I've actually been a member here for a while but couldn't for the life of me remember my last username or e-mail address.
I was helped by a member of another forum who pointed me to the Factory pattern at [php.net...]
I was unaware that you could do something like this:
eg:
$classname = 'MXRecord';
$class = new $classname('', '', '', etc);
but it seems to have solved this problem.
thanks for the assistance.
[edited by: coopster at 2:28 pm (utc) on Mar. 11, 2009]
[edit reason] removed period so link works [/edit]