What is Inheritance in PHP?

In this tutorial we will explain inheritance in PHP, a mechanism that allows a child class to inherit properties and methods from a parent class enabling code reusability. Inheritance is considered one of the four pillars of object-oriented programming.

The four pillars of object-oriented programming are:

Abstraction
Encapsulation
Inheritance
Polymorphism

A parent class is also called a superclass or base class.

A child class is also called a subclass or derived class.

Let's assume we have a class named Vehicle. A vehicle can have properties like name and color. We can define variables like $name and $color to hold the values of these properties.

Objects of a class are created using the new keyword.

In a class, variables are called properties and functions are called methods.

<?php 

    // Parent class 
    class Vehicle {
        // Properties 
        public $name;
        public $color;

        // Methods 
        public function __construct($name, $color) {
            $this->name = $name;
            $this->color = $color;
        }
        public function intro() {
            echo "The vehicle is {$this->name} and the color is {$this->color}.";
        }
    }

    // Child class
    class Yukon extends Vehicle {
        public function message() {
            echo "Am I a sedan or SUV? ";
        }
    }
    $yukon = new Yukon("Yukon", "black");
    $yukon->message();
    $yukon->intro();

?>

The Yukon class is inherited from the Vehicle class.

The "extends" keyword is used to indicate that a class inherits from another class.

When extending a class, the child class will inherit all the public and protected methods, properties and constants from the parent class. In addition, it can have its own properties and methods.

PHP only supports single inheritance.

Popular

Related articles

How to Change Your WordPress Admin Username via MySQL Command Line

In this guide, we're going to teach you how to use the MySQL Command Line to change a WordPress username and author slug directly via an SQL query.

Getting Started with React

In this guide, we will cover the basics of setting up a local development environment, starting a simple React project, and the basics of how it works.

How to Create Bash Aliases

This tutorial demonstrates how to use the alias command to create personalized shortcuts, which can help you save time and feel less frustrated.

Using Git for PHP Development

This guide walks through the fundamentals of Git. In this tutorial, we will show you Git commands. For Linux you can use the built-in terminal.

How to Connect to MySQL with Laravel

In this guide, you will learn how to connect your Laravel application to your MySQL database.

How do you change the default SSH Port on CentOS Stream 9?

Changing the default SSH port adds an extra layer of security by reducing the risk of your password being cracked from a brute force attack.