PHP Inheritance
Inheritance allows a class to reuse properties and methods from another class. The child class extends the parent class and can override its methods.
extends and parent::
Use extends to inherit from a parent class. Use parent:: to call the parent's constructor or methods from the child.
<?php
class Animal {
protected string $name;
protected string $sound;
public function __construct(string $name, string $sound) {
$this->name = $name;
$this->sound = $sound;
}
public function speak(): string {
return "{$this->name} says {$this->sound}";
}
public function describe(): string {
return "I am {$this->name}";
}
}
class Dog extends Animal {
private string $breed;
public function __construct(string $name, string $breed) {
parent::__construct($name, "Woof"); // call parent constructor
$this->breed = $breed;
}
// Method overriding
public function speak(): string {
return parent::speak() . "! (breed: {$this->breed})";
}
public function fetch(): string {
return "{$this->name} fetches the ball!";
}
}
$dog = new Dog("Rex", "Labrador");
echo $dog->speak(); // Rex says Woof! (breed: Labrador)
echo $dog->describe(); // I am Rex (inherited)
echo $dog->fetch(); // Rex fetches the ball!
// instanceof operator
echo ($dog instanceof Dog) ? "Is a Dog\n" : "";
echo ($dog instanceof Animal) ? "Is an Animal\n" : "";
?>
final Classes and Methods
Mark a class or method as final to prevent it from being extended or overridden.
<?php
class Vehicle {
public string $type;
public function __construct(string $type) {
$this->type = $type;
}
// This method cannot be overridden
final public function getType(): string {
return $this->type;
}
}
class Truck extends Vehicle {
public int $payload;
public function __construct(int $payload) {
parent::__construct("Truck");
$this->payload = $payload;
}
// Cannot override getType() — it's final
}
// Final class — cannot be extended
final class Singleton {
private static ?Singleton $instance = null;
private function __construct() {}
public static function getInstance(): Singleton {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
$s1 = Singleton::getInstance();
$s2 = Singleton::getInstance();
var_dump($s1 === $s2); // true — same instance
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.