Inheritance in Object Oriented PHP

Timothy Iloba
9 min readMar 5, 2024

--

Have you noticed that you inherited some traits from your parents?? Well, for me I inherited some traits from my mum. I wouldn’t want to start talking about them here because it is not the purpose of this blog.

Hey everyone, welcome to this blogpost and in this one, we will be discussing inheritance. Inheritance is a very important concept in the world of object-oriented programming and in this blogpost, I will be breaking it down in an easy to understand way for you in PHP.

As we have earlier mentioned, Inheritance is one of the principles of Object-Oriented Programming. To make you understand clearly, a principle is simply a rule that guides something. So, when we say Inheritance is one of the principles of Object-oriented programming, what we simply mean is that Inheritance is one of the rules that guides the use of object-oriented programming and makes it what it is. Let’s dive deeper.

We have earlier mentioned that inheritance is a principle of OOP and like we now understand, a principle is a rule. The question now is, what is this Inheritance rule all about? It’s very simple and straightforward. Inheritance, as a principle of OOP states that a Child Class can inherit properties and methods from a Parent Class. Pay attention to these two keywords. The ‘Child Class’ and ‘Parent Class’.

Remember how we started earlier? I shared that I inherited some traits from my mom? Well, that’s simply what inheritance is all about.

Inheritance allows Child Classes to inherit methods and properties from a Parent Class. Let us look at a simple example in our code. In this code example, I will be using an analogy of a father and a son to show you how inheritance works.

First, we will have our Father Class

<?php

class Father
{
public string $name = "Father";

public function allBusinesses(): string{
return "All Businesses” . PHP_EOL;
}

public function allProperties(): string{
return "All Properties". PHP_EOL;
}
}

From the code above, we can see the father class. It has one property that holds the name of the father and two methods. The first method is the allBusinesses method and the second is the allProperties methods. In this instance, the Father Class will be our Parent Class. It will be providing the properties and methods that the second class will inherit from. Let’s take a look at the second class.

<?php

class Son extends Father
{

}

Here is the second class, the Son class. As you can see, the Son class is empty. It does not really contain any code but I want you to notice something. After the Son, did you notice the keyword “extends”? I am sure you did. The extends keyword is used whenever we want to inherit properties and methods from a parent class. In this case, we are inheriting from the Father Class.

Now that we have created our Son class and have inherited properties and methods from the father Class using the extends keyword, what next?

First, we need to understand what goes on behind the scenes whenever we extend a parent class. Whenever a child class extends a parent class, that child class inherits all public properties and methods from the parent class.

So, in our case, our Son class will have access to all the public properties and methods on the parent class. Let’s test this out

<?php

require_once 'Father.php';
require_once 'Son.php';

$son = new Son();

print $son->allProperties();
print $son->allBusinesses();

From our code above, you can see that we have created a new Son object by instantiating the class and you can see that we are now calling the Allproperties and allBusinesses methods which are on the parent class. Let’s see the result

All Properties
All Businesses

So, you can see that we are getting the right results. We were able to inherit the allProperties and allBusinesses methods from the father class just like we can also in the real world inherit properties and businesses from our biological Parents. Remember that our Son class did not have any methods of its own. It only inherited the methods from the Father class. Take a look at it again.

<?php

class Son extends Father
{

}

I believe you’ve now understood this principle of OOP called inheritance. It simply allows for child classes to inherit properties and methods from their Parent Classes.

One of the benefits of inheritance is Code reusability. Inheritance helps us to reuse code thereby reducing code duplication. This simply means Inheritance helps us to reuse methods or properties we need anywhere in our program instead of having to copy and paste the code wherever we need it. Let’s take a look at this example.

Let’s paint this scenario together. Let’s say we are working on a software that calculates the Tax for both government workers and private workers. In this scenario, both of these workers pay the same percentage of tax which is 10%. Let’s jump into code.

<?php

class GovernmentWorker
{
public string $name;

public int $salary = 10000;

public function calculateTax(): int
{
return $this->salary * 10 /100;
}
}

Here we have a government worker class and you can see its properties and methods. Next, we will have the private workers class

<?php

class PrivateWorker
{
public string $name;

public int $salary = 9000;

public function calculateTax(): int
{
return $this->salary * 10 /100;
}
}

The private worker class as you can see also has its own properties and methods. You can calculate the tax on each of the above classes. Everything looks fine but however, there is a problem. What is this problem you may ask? The problem we have here is a problem of code duplication. You can see that in the GovernmentWorker and PrivateWorker class, the calculateTax method exists and guess what, it is simply doing the same thing, calculating the tax using the same logic.

We need to figure out a way where we will just have our calculateTax method in one place and then inherit it. Instead of copying the method to each class where we need it. Imagine that we are to add 100 more kinds of workers whom we are to calculate tax for. Will it make sense to copy the calculateTax method and paste in all of them, the answer is No. We are trying to avoid code duplication as much as possible.

So, let’s find a solution to our problem. From the top of my mind, I can already figure out a solution. How about we take the calculateTax method which we will need in several parts of the program and put it in a base class and then whenever we need to calculateTax, all we will do is inherit the method from the base Class. Let’s take a look

<?php

class Worker
{
public function calculateTax(): int
{
return $this->salary * 10 /100;
}

}

Above, we have a Worker class and as you can see, I also added the CalculateTax method to it. Now wherever we need to use the method, all we will have to do is extend the Worker class and inherit the method from it.

Take a look below

<?php

require_once 'Worker.php';
class GovernmentWorker extends Worker
{
public string $name;

public int $salary = 10000;
}

Above, we are extending the Worker class, thereby inheriting the method CalculateTax and we will be able to call the method. See below:

<?php


require_once 'GovernmentWorker.php';

$governmentWorker = new GovernmentWorker();
$tax = $governmentWorker->calculateTax();

print $tax;

Can you see how we were able to calculate the tax using the CalculateTax method we inherited?

Take a look at the result below

1000

Now we have been able to calculate the tax for government workers. The next is to calculate the tax for private workers using the same method we used above. We are going to inherit the method from the Base Worker class and then use it.

<?php

require_once 'Worker.php';

class PrivateWorker extends Worker
{
public $name;

public int $salary = 9000;

}

Now, let’s use the method to calculate the tax for the private workers.

<?php


require_once 'PrivateWorker.php';

$privateWorker = new PrivateWorker();
$tax = $privateWorker->calculateTax();

print $tax;

Now take a look at the results

900

So, we just demonstrated one of the benefits of inheritance which is code reuse. Code reuse simply helps us to avoid code duplication and that makes our code cleaner.

Another thing I will love to share with you is that whenever a child class inherits properties and methods from a parent class, the child class can override the method or properties it inherited and modify them to suit its needs.

Imagine that you inherited a business from your parents and then, as you began to run the business, you discovered that you could run it in a better way and that then made you bring in some innovations that helped you build the business to your taste.

That’s how it is when it comes to inheritance in OOP. Child classes can override the methods and properties they inherited from their parent classes.

Now, let’s go back to our software that calculates tax and demonstrate this. Remember that both the PrivateWorker and GovernmentWorker class inherit the calculateTax method from the Parent Worker class. And that method simply calculates the tax as 10% of their salary. Imagine that later on, the Government decides to reduce the tax rate for its workers to 5%. From looking at our program, we can see that there is a problem. We are inheriting the calculateTax method from the base class, and it calculates the tax as 10%. How do we fix this? How do we make sure that the tax for GovernmentWorkers is now 5% instead of 10%? It’s simple and easy. Remember, the Child class can override the methods and properties it inherited from the parent class.

We will simply do this by defining our own calculateTax method in the Government class with the same name, and implement the method to suit our new need which is to make tax 5%.

Let’s look at it in code.

<?php

require_once 'Worker.php';
class GovernmentWorker extends Worker
{
public string $name;

public int $salary = 10000;

public function calculateTax(): int
{
return $this->salary * 5 /100;
}

}

From what we can see above, we can see that we now declared a calculateTax method on the Government Class which is the child class we are interested in modifying and this time, it is calculating the tax as 5%. You might be wondering, what is going on here? Let me explain. Remember that we are currently extending the base Worker class (parent class) and inheriting the calculateTax method from it. That method we are inheriting calculates tax as 10% but we do not want that on our Government Class. We want to calculate our tax as 5% based on the new government policy so all we are doing is overriding the calculateTax method we inherited from the parent class on the child class and implementing it our own way. Now, we are calculating tax as 5%. The privateWorkers tax will still be 10%. Remember, we are overriding the CalculateTax method on the Government Class.

Let’s test our code out

<?php


require_once 'GovernmentWorker.php';


$governmentWorker = new GovernmentWorker();
$tax = $governmentWorker->calculateTax();

print $tax;

The results we will get will no longer be 1000 which is 10% of 10000 but will now be 500 because we overrode the method we inherited and implemented it in our own way in the child class (Government Class). Take a look below:

500

I hope you understand? A thing to note is that whenever you are overriding a method on the child class, make sure your new method has the same name as the one you are inheriting. As you can see above, when overriding the calculateTax method on the Government Class (Child Class), we gave it the same name it had from the parent class.

That’s it. Tomorrow, if there is a new policy that affects the tax rate for privateWorkers, we can do the same and override the calculateTax method it inherited and implement it our own way.

Wrapping up, I will love to clearly state that there is more to inheritance than just the basics we just covered. Inheritance is a principle that is most times misunderstood. Most developers use it the wrong way which ends up messing up their code. Understanding how to use inheritance the right way will help you as a developer and also make you stand out.

Will you love to learn more about inheritance and how to use it the right way? Then feel free to check out this full php Object oriented course from the guy who taught me:

https://garyclarketech.teachable.com/p/learn-object-oriented-php. Everything you need to understand Object Oriented programming is covered there. Inheritance is also covered in depth.

You can grab yours now and get a 20% discount. All you have to do is use this promo code: GCTREPO20 when making your purchase.

You can access all the codes used in this post here: https://github.com/GaryClarke/blog-code-examples/tree/6-understanding-inheritance

Thanks for reading. Till next time.

--

--

Timothy Iloba

Let's work our way up into being world class PHP developers. We will focus on understanding the basics and important concepts as that is what will set us apart.