views:

130

answers:

3

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).

A: 

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

Factory

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

Then try searching for "php factory pattern implementation"

Peter
+5  A: 

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

Justin Niessner
Yes! This is exactly it. I found the "Design Patterns in PHP" the most helpful. The other PHP article was a bit confusing for me as it talked about Abstraction at the same time.
Matt McCormick
+2  A: 

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.

Chris B.