PHP Inheritance Using the Extends Keyword

In PHP, inheritance is a fundamental concept of object-oriented programming that allows a child class to inherit properties and methods from a parent class. This article explains how the extends keyword facilitates this relationship, how to override methods, how to use the parent keyword, and the rules governing visibility modifiers in inherited classes.

Understanding the Extends Keyword

To establish an inheritance relationship in PHP, you use the extends keyword in the child class declaration. The child class immediately gains access to all non-private properties and methods of the parent class, promoting code reuse and reducing duplication.

class Vehicle {
    public $brand;

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

    public function honk() {
        return "Beep beep!";
    }
}

// Car inherits from Vehicle
class Car extends Vehicle {
    public $model;
}

$myCar = new Car();
$myCar->setBrand("Toyota"); // Inherited method
echo $myCar->honk();        // Output: Beep beep!

Visibility Modifiers in Inheritance

How a child class interacts with inherited properties and methods depends on their visibility modifiers:

Method Overriding

A child class can redefine a method inherited from the parent class to alter its behavior. This is known as method overriding. When the overridden method is called on an instance of the child class, the child’s version of the method runs.

class Animal {
    public function makeSound() {
        return "Generic animal sound";
    }
}

class Dog extends Animal {
    // Overriding the parent method
    public function makeSound() {
        return "Bark!";
    }
}

Using the parent:: Keyword

If you override a method but still want to execute the original logic from the parent class, you can use the parent:: scope resolution operator. This is commonly used in constructors to ensure the parent class is initialized properly.

class Employee {
    protected $name;

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

class Manager extends Employee {
    private $department;

    public function __construct($name, $department) {
        // Call the parent constructor
        parent::__construct($name);
        $this->department = $department;
    }
}

Key PHP Inheritance Rules

  1. Single Inheritance: PHP only supports single inheritance. A class can extend only one parent class.
  2. The final Keyword: If a parent class is marked as final, it cannot be extended. Similarly, if a parent method is marked as final, child classes cannot override it.
  3. Type Compatibility: An instance of a child class also passes type-checks for the parent class (polymorphism).