Composition over Inheritance in PHP

Composition over Inheritance in PHP

Reasons to use Composition over Inheritance in PHP

Inheritance vs Composition

1. Static vs Dynamic Behavior The first difference between Inheritance and Composition comes from a flexible point of view. When you use Inheritance, you have to define which class you are extending in code, it cannot be changed at runtime, but with Composition, you just define a Type which you want to use, which can hold its different implementation. In this sense, Composition is much more flexible than Inheritance.

2. Limited code reuse with Inheritance With Inheritance, you can only extend one class, which means your code can only reuse just one class, not more than one. If you want to leverage functionalities from multiple classes, you must use Composition.

3. Unit Testing Better unit testing with Composition.

4. Fixes lack of multiple inheritances With composition, single inheritance languages, such as PHP, can easily overcome the lack of multiple inheritances.


class Animal {
    function eat() 
    {
        echo "Eating...<br>";
    }
}

class Walkable {
    function walk() 
    {
        echo "Walking...<br>";
    }
}

class Swimmable {
    function swim() 
    {
        echo "Swimming...<br>";
    }
}

class Flyable {
    function fly() 
    {
        echo "Flying...<br>";
    }
}

class Fish {

    private $animal;
    private $swimmable;

    function __construct(Animal $animal, Swimmable $swimmable) 
    {
        $this->animal = $animal;
        $this->swimmable = $swimmable;
    }

    public function action() 
    {    
        $this->animal->eat();    
        $this->swimmable->swim();
    }
}

class Bird {

    private $animal;
    private $walkable;
    private $swimmable;
    private $flyable;

    function __construct( Animal $animal, Walkable $walkable, Swimmable $swimmable, Flyable $flyable ) 
    {
        $this->animal = $animal;
        $this->walkable = $walkable;
        $this->swimmable = $swimmable;
        $this->flyable = $flyable;
    }

    public function action() 
    {    
        $this->animal->eat(); 
        $this->walkable->walk();   
        $this->swimmable->swim();
        $this->flyable->fly();
    }
}

echo "Nemo the fish's activities:<br>";
$animal = new Animal();
$swimmable = new Swimmable();
$nemo = new Fish($animal, $swimmable);
$nemo->action();


echo "<br>";

echo "Tweety the bird's activities:<br>";
$animal = new Animal();
$walkable = new Walkable();
$swimmable = new Swimmable();
$flyable = new Flyable();

$tweety = new Bird($animal, $walkable, $swimmable, $flyable);
$tweety->action();

Image Credit