← Back to PHP Course | Chapter 8: OOP | Lesson 5 of 14

PHP Inheritance

What is Inheritance?

Inheritance lets one class (the child) reuse the properties and methods of another class (the parent) using the extends keyword, avoiding duplicating shared logic across related classes.

Example: What is Inheritance?

php
<?php
class Animal {
    function eat() {
        echo "Eating...\n";
    }
}
class Dog extends Animal {
}
$dog = new Dog();
$dog->eat();
?>

Defining Parent and Child

A child class automatically has access to all of its parent's public and protected members without redeclaring them, and can add new properties or methods of its own on top of what it inherited.

Example: Defining Parent and Child

php
<?php
class Animal {
    public $name = "Generic Animal";
    function eat() {
        echo "Eating\n";
    }
}
class Dog extends Animal {
    function bark() {
        echo "Barking\n";
    }
}
$dog = new Dog();
$dog->eat();
$dog->bark();
?>

Inheriting Protected Members

parent::__construct() lets a child class's constructor explicitly call its parent's constructor, ensuring the inherited part of the object is initialized correctly before the child adds its own setup logic.

Example: Inheriting Protected Members

php
<?php
class Animal {
    public $name;
    function __construct($name) {
        $this->name = $name;
    }
}
class Dog extends Animal {
    function __construct($name) {
        parent::__construct($name);
    }
}
$dog = new Dog("Rex");
echo $dog->name;
?>

The final Keyword

PHP only supports single inheritance for classes — a class can extend just one parent — though it can implement multiple interfaces, which is how PHP works around the ambiguity problems of true multiple inheritance.

Example: The final Keyword

php
<?php
interface Swims {}
interface Flies {}
class Duck implements Swims, Flies {
}
$duck = new Duck();
var_dump($duck instanceof Swims);
?>

Inheritance for Web Tools

A good inheritance relationship models a genuine is-a relationship, like Dog extends Animal, rather than being used just to reuse unrelated code, which tends to produce fragile, confusing class hierarchies.

Example: Inheritance for Web Tools

php
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Animal);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.