PHP Inheritance
In this page:
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
class Animal {
function eat() {
echo "Eating...\n";
}
}
class Dog extends Animal {
}
$dog = new Dog();
$dog->eat();
?>
Login to try C/C++/Java/PHP code in the editor
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
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();
?>
Login to try C/C++/Java/PHP code in the editor
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
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;
?>
Login to try C/C++/Java/PHP code in the editor
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
interface Swims {}
interface Flies {}
class Duck implements Swims, Flies {
}
$duck = new Duck();
var_dump($duck instanceof Swims);
?>
Login to try C/C++/Java/PHP code in the editor
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
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Animal);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: