Tutorial :OO Design: Returning a child class from a parent


I'm still a novice when it comes to polymorphism so I hope I can phrase my question correctly.

Let's say I have tables in my Database - Dog, Cat and Mouse. I want to be able to call something like:

$animal = new Animal("dog", 12);  

with the animal class being something like:

class Animal {    protected $id;    protected $legs;    protected $height;    function __construct($type, $id) {      if ($type == "dog") {        return new Dog($id);      }    }  }    class Dog extends Animal {    function __construct($id) {      $this->id = $id;      $this->legs = 4;      $this->height = 1;    }  }  

This doesn't work but I want to be able to call a new Animal and pass in the specific animal and have it be returned. How can I design this? (I'm using PHP).


What you're looking for is actually a design pattern called the Factory Pattern. You can read up on it here:

Factory Pattern

And some longer articles for PHP:

Design Patterns in PHP
The Basics of Using Factory Pattern in PHP


What you want is a "Factory Pattern". Rather than create new Animals directly, call a function which chooses the type of animal to create. In Java I'd probably make that a static method of the class, and in Python I'd store all the Animal classes in a dictionary linked to the key, so I could look up the key and then pass the arguments along to the constructor.

For PHP, I found an article on Using the Factory Pattern in PHP.


I don't know php but if it helps the design pattern you are talking about is called


Try searching for "gang of four Factory" for an explanation of the pattern.

Then try searching for "php factory pattern implementation"

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »