PHP — Inheritance
Basic inheritance
<?php
class Animal {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function speak(): string {
return "The animal speaks";
}
}
class Dog extends Animal {
public function speak(): string {
return "{$this->name} barks";
}
}
$dog = new Dog("Rex");
echo $dog->speak(); // Rex barks
?>
Protected and private
<?php
class Parent {
protected int $x = 10;
private int $y = 20;
public function getX(): int { return $this->x; }
}
class Child extends Parent {
public function show(): void {
echo $this->x; // OK: protected
// echo $this->y; // Error: private
}
}
?>
Constructor chaining
<?php
class Person {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
class Employee extends Person {
public string $company;
public function __construct(string $name, string $company) {
parent::__construct($name);
$this->company = $company;
}
}
$emp = new Employee("Alice", "TechCorp");
echo "{$emp->name} works at {$emp->company}";
?>
Final classes and methods
<?php
final class Immutable {
public function __construct(public string $value) {}
}
// class Child extends Immutable {} // Error: cannot extend final
class Base {
final public function show(): void {
echo "Cannot override";
}
}
class Child extends Base {
// public function show(): void {} // Error: cannot override final
}
?>
Abstract classes
<?php
abstract class Shape {
abstract public function area(): float;
public function describe(): string {
return "Area: " . number_format($this->area(), 2);
}
}
class Circle extends Shape {
public function __construct(private float $radius) {}
public function area(): float {
return M_PI * $this->radius ** 2;
}
}
$circle = new Circle(5);
echo $circle->describe(); // Area: 78.54
?>
Mini Practice
Write PHP code that:
- Creates a parent and child class
- Uses protected properties
- Chains constructors with parent::__construct()
- Demonstrates final class
Up Next
In the next lesson, you'll learn about Interfaces — defining contracts in PHP.
Related Topics
Frequently Asked Questions about Inheritance
What is Inheritance in PHP?
Inheritance is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Inheritance?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Inheritance.
Why is Inheritance important in PHP?
Inheritance is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.