Inheritance in PHP

Inheritance in PHP

I hope my last post about interfaces didn’t make anyone cry. Even if you didn’t understand it; I hope you keep reading. You may have an “aha!” moment when you least expect it. The last post ran a little longer than I originally wanted, so I’ll try to keep this post briefer.

Inheritance is something you get from a rich aunt or uncle when they pass away, but it’s also something that objects can get from another object. Back to our Person class, you may want to create a Boy class. A boy (unless your Pinocchio) shares the same properties a Person does. Boys eat, pee, and poop, but they may not wash their hands (I know it’s gross, but I already started down this road, and I’m not turning back). You don’t want to write the same methods for the Boy class, that would be a waste of time, so we will extend(s) the Person class as shown below. Here is a link to a gist on GitHub with the code.


<?php
class Boy extends Person {

}

The Boy class now has all the same properties and methods that the Person class does! However, boys don’t wash their hands, so we need to fix that. We can override the washHands() method in the Person class by writing it in the Boy class like shown below.


<?php
class Boy extends Person {
  public function washHands() {
    echo "I don't wash my hands...";
  }
}

Now if we were to instantiate a Boy class and call the washHands() method, it would output “I don’t wash my hands…” as shown below.


<?php
$boy = new Boy("Felix", 4);
$boy->washHands(); // OUTPUT: I don't wash my hands...
// Gross.

Since the Boy class extends the Person class, it has the same construct and requires the same parameters. Here is what php.net has to say about Object Inheritance:

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

I like my explanation better. There is more to inheritance, but I’ll cover that in another post. Keep practicing, reading, and learning. Email me if you need help, if you have questions, or if I messed something up.