Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

Inheritance v Composition, how to use it?

Object oriented theory has it that you should distinguish between is-a and has-a, to chose between inheritance and composition, but in practice this model soon breaks down. The problem is that the distinction isn't as black-and-white as it's made out to be; Real things get their meaning from a context, so when the context changes, they may change their meaning. Inheritance - being a static relationship - doesn't support this.

      
        // if you decided that employer is a person,
        // you can use inheritance here
        class Person {
        function sayHello() {
          echo "Hello, World!";
        }

        }
        class Employer extends Person{
          ...
        }

        // when you know a car has a wheel,
        // then composition is good
        class Wheel {
          function spinning {
            echo "Spinning!";
          }
        }

        class Car {
          protected $wheel;
          function __construct() {
            $this->wheel = new Wheel();
          }
          function spinning() {
            $this->wheel->spinning();
          }
        }