PHP ยท Chapter 37 of 44

PHP Inheritance

Inheritance lets a class (called a child or subclass) reuse the properties and methods of another class (called a parent or superclass), using the extends keyword. This helps avoid duplicating shared logic across related classes.

A child class can override a parent's methods to provide its own specific behavior, and can still call the parent's version of a method using parent::methodName().

Syntax
class Child extends ParentClass {
  function method() {
    parent::method();
  }
}

Extending a class

class Dog extends Animal { } makes Dog inherit all public and protected properties and methods from Animal, while also allowing Dog to add its own.

Overriding methods

A child class can redefine a method with the same name as one in the parent, replacing its behavior. parent::method() calls the original parent implementation if needed.

Example 1 (php)
<?php
  class Animal {
    function speak() {
      return "Some sound";
    }
  }
  class Dog extends Animal {
    function speak() {
      return "Woof!";
    }
  }
  $d = new Dog();
  echo $d->speak();
?>
Output
Woof!

Dog overrides Animal's speak() method to return its own specific sound.

Example 2 (php)
<?php
  class Vehicle {
    function info() {
      return "A vehicle";
    }
  }
  class Car extends Vehicle {
    function info() {
      return parent::info() . " that drives on roads";
    }
  }
  echo (new Car())->info();
?>
Output
A vehicle that drives on roads

parent::info() calls the original method and extends its result in the child class.

Key points

  • extends allows a class to inherit from another class.
  • Child classes can override parent methods with their own logic.
  • parent::method() calls the parent class's original implementation.
  • Inheritance reduces duplicated code between related classes.
๐Ÿ’ก Note: PHP only supports single inheritance โ€” a class can extend only one parent class directly.

๐Ÿ“ Quick Quiz

1. Which keyword lets a class inherit from another?

2. How do you call a parent class's original method from a child?

3. Can a PHP class extend more than one class directly?