Object inheritance in PHP

The fun in object oriented programming starts when we allow classes to inherit properties and methods from other classes.

Suppose you have an Animal class:

class Animal {

}

Every animal has an age, and every animal can eat. So we add a age property and an eat() method:

class Animal {
  public $age;

  public function eat() {
    echo 'the animal is eating';
  }
}

A dog is an animal and has an age and can eat too, so the Dog class instead of reimplementing the same things we have in Animal can extend that class:

class Dog extends Animal {

}

We can now instantiate a new object of class Dog and we have access to the properties and methods defined in Animal:

$roger = new Dog();
$roger->eat();

In this case we call Dog the child class and Animal the parent class.

Inside the child class we can use $this to reference any property or method defined in the parent, as if they were defined inside the child class.

It’s worth noting that while we can access the parent’s properties and methods from the child, we can’t do the reverse.

The parent class knows nothing about the child class.

What happens if we have a eat() method in Animal and we want to customize it in Dog? We can override that method.

class Animal {
  public $age;

  public function eat() {
    echo 'the animal is eating';
  }
}

class Dog extends Animal {
  public function eat() {
    echo 'the dog is eating';
  }
}

Now any instance of Dog will use the Dog’s implementation of the eat() method.

Now that we introduced inheritance we can discuss protected. We already saw how we can use the public access modifier to set properties and methods callable from outside of a class, by the public.

private properties and methods can only be accessed from within the class.

protected properties and methods can be accessed from within the class and from child classes.

Download my free PHP Handbook!