Web Development Handbook

Web Development Handbook

Development is fun in a funny way

PHP OOP - Inheritance Basics
PHP

PHP OOP - Inheritance Basics

0 votes
0 votes
0 comments
245 views
Share

By Nihar Ranjan Das, Published on May 12th 2023 | 4 mins, 347 words

We all know PHP is an object-oriented programming language and inheritance is a fundamental concept of PHP that allows you to create new classes based on existing classes. Inheritance enables code reuse and promotes the concept of "is-a" relationships between classes.

To define a class that inherits from another class in PHP, you use the extends keyword. The class that is being inherited from is called the parent class or superclass, while the class that inherits from it is called the child class or subclass. The child class inherits all the properties (variables) and methods (functions) of the parent class and can also have its own additional properties and methods.

Here's an example to illustrate inheritance in PHP:

class Vehicle {
    protected $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function getBrand() {
        return $this->brand;
    }

    public function drive() {
        echo "Driving the {$this->brand}\n";
    }
}

class Car extends Vehicle {
    private $model;

    public function __construct($brand, $model) {
        parent::__construct($brand);
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }

    public function drive() {
        echo "Driving the {$this->brand} {$this->model}\n";
    }
}

// Create an instance of the Car class
$car = new Car('Toyota', 'Camry');

// Access the inherited method from the parent class
echo $car->getBrand();  // Output: Toyota

// Access the method specific to the Car class
echo $car->getModel();  // Output: Camry

// Call the overridden method in the Car class
$car->drive();  // Output: Driving the Toyota Camry


In the example above, we have a Vehicle class with a property $brand and two methods: getBrand() and drive(). The Car class extends the Vehicle class using the extends keyword. It adds an additional property $model and overrides the drive() method with its own implementation.

By using inheritance, the Car class inherits the getBrand() method from the Vehicle class and can access it directly. It also has its own method getModel() and an overridden drive() method that provides a different implementation.

Inheritance allows you to create a hierarchy of classes, with each subclass building upon the functionality of its parent classes while adding its own specific features.

If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.