OOP: Inheritance & Overriding

🐘 PHP Lesson 9 Intermediate

Inheritance derives child classes from parent classes. PHP supports single inheritance and provides the parent scope resolution operator to invoke parent methods.

1 parent:: Overriding & static bindings

PHP subclasses inherit from parent classes using the **`extends`** keyword: `class Child extends Parent`. When overriding a parent method, you can invoke the parent class's original implementation using the scope resolution operator: **`parent::method()`**.

2 Inheritance Code

Let's run a program demonstrating class inheritance, overrides, and invoking parent methods:

PHP — Inheritance ▶ Run Code
<?php
class Animal {
    public $name;

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

    public function makeNoise(): string {
        return "Generic animal sound";
    }
}

// Dog extends Animal
class Dog extends Animal {
    public function makeNoise(): string {
        // Call parent method
        return parent::makeNoise() . " - Woof! Woof!";
    }
}

$dog = new Dog("Buddy");
echo $dog->makeNoise() . "\n";
?>
3 Code Challenge
Challenge: Create a parent class called `Vehicle` and a child subclass called `Truck`. Override a method `startEngine()` in `Truck` that invokes parent checks first, then prints "Diesel roaring".