Inheritance in PHP. How to build upon existing classes.

Inheritance in PHP gives a class the ability to inherit properties and methods from another class. The class being inherited from is called the parent, while the class that inherits it is called the child.

This feature of PHP enables developers to build upon existing classes, modifying their features or adding new ones while keeping the original code intact.

The syntax is as follows:

class ParentClass {
  // Properties and methods
}
class ChildClass extends ParentClass {
  // Additional or overridden properties and methods
}

Let’s see an example to better understand this concept:

A class with public and protected properties and methods.

Here, we have a User class with three properties. $name and $email which are public, and a protected property $status.

We also have a constructor that takes as parameters a name and an email. And also a public method that resembles a dummy login.

We can create an Admin class that extends this User class:

Code example of a class that extends our previous User class.

We can create specific properties for that class. Let’s say we create the public property $level to grant permissions according to its value.

We must be able to pass in this property when we instantiate a new admin.

But we are also able to make use of the User class’s constructor properties ($name, $email) through inheritance:

Code example of using the parent constructor syntax.

We can “inherit” what is in the parent constructor by using the parent constructor syntax.

This calls the constructor of the parent class.

Now, when instantiating a new admin, we can pass the name and email parameters that the Admin class inherits from the User class:

Code example of instantiating a new object and inheriting properties also from the parent class.

Inheriting Protected properties and methods

Inheritance works in properties and methods using the protected access modifier when a class is a subclass on a parent class.

In our case say we want admin to have access to the $status property of the parent User class.

We can achieve this with the use of a getter since the $status property is protected.

Code example of accessing a protected property with the use of a getter.

Inheritance and Polymorphism

Overriding methods and properties is allowed.

Let’s say we want to create a special login() method for the Admin child class.

We can just overwrite the parent method by creating a new one, slightly different, in the Admin class.

Code example of overriding the parent method.

Here we create another subclass with the name GameUser that inherits the original login method from the parent.

Let’s see what we get when we call both:

Code example of how calling the same method we get two different results.

By calling the same method we get two different results.This is an example of polymorphism.

Although my blog doesn’t support comments, feel free to reply via email or X.