PHP Inheritance — Complete Guide to Class Inheritance and Method Overriding
In this tutorial, you will learn about PHP Inheritance. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP inheritance allows a class (child) to inherit properties and methods from another class (parent), enabling code reuse and establishing hierarchical relationships.
What You'll Learn
By the end of this tutorial, you'll use extends, parent keyword, method overriding, final keyword, abstract classes, and leverage polymorphism through inheritance.
Why Inheritance Matters
Inheritance eliminates code duplication by sharing common functionality between related classes. It models real-world relationships (a Car is-a Vehicle) and enables polymorphic behavior.
Real-World Use
A payment system has a base PaymentMethod class with shared logic. CreditCard, PayPal, and BankTransfer extend it, each implementing their own processPayment method.
Inheritance Learning Path
flowchart LR
A[Classes/Objects] --> B[Inheritance]
B --> C[Interfaces]
C --> D[Traits]
D --> E[Namespaces]
A --> F{You Are Here}
style F fill:#f90,color:#fff
Basic Inheritance
<?php
class Animal {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function speak(): string {
return "Some sound";
}
}
class Dog extends Animal {
public function speak(): string {
return "Woof! I am " . $this->name;
}
}
$dog = new Dog("Buddy");
echo $dog->speak(); // Woof! I am Buddy
The parent Keyword
<?php
class Vehicle {
protected string $brand;
protected int $speed = 0;
public function __construct(string $brand) {
$this->brand = $brand;
}
public function describe(): string {
return "A {$this->brand} vehicle";
}
}
class Car extends Vehicle {
private int $doors;
public function __construct(string $brand, int $doors) {
parent::__construct($brand);
$this->doors = $doors;
}
public function describe(): string {
return parent::describe() . " with $this->doors doors";
}
}
$car = new Car("Toyota", 4);
echo $car->describe(); // A Toyota vehicle with 4 doors
Abstract Classes
<?php
abstract class Database {
protected string $host;
abstract public function connect(): bool;
abstract public function query(string $sql): array;
public function __construct(string $host) {
$this->host = $host;
}
}
class MySQLDatabase extends Database {
public function connect(): bool {
echo "Connecting to MySQL at {$this->host}\n";
return true;
}
public function query(string $sql): array {
echo "Executing: $sql\n";
return [["id" => 1, "name" => "Alice"]];
}
}
$db = new MySQLDatabase("localhost");
$db->connect();
print_r($db->query("SELECT * FROM users"));
Final Keyword
<?php
class BaseConfig {
final public function getVersion(): string {
return "1.0.0";
}
}
class ExtendedConfig extends BaseConfig {
// This would cause a fatal error:
// public function getVersion(): string { return "2.0"; }
}
Polymorphism
<?php
interface NotificationChannel {
public function send(string $message): bool;
}
class EmailChannel implements NotificationChannel {
public function send(string $message): bool {
echo "Email: $message\n"; return true;
}
}
class SMSChannel implements NotificationChannel {
public function send(string $message): bool {
echo "SMS: $message\n"; return true;
}
}
function notify(NotificationChannel $channel, string $msg): void {
$channel->send($msg);
}
notify(new EmailChannel(), "Hello!"); // Email: Hello!
notify(new SMSChannel(), "Urgent!"); // SMS: Urgent!
Common Mistakes
1. Deep Inheritance Hierarchies
More than 3 levels of inheritance is hard to maintain. Prefer Composition Over Inheritance for complex hierarchies.
2. Forgetting to Call parent::__construct
Child constructors don't automatically call parent constructors. Use parent::__construct() explicitly.
3. Weakening Access in Overridden Methods
Overridden methods must have equal or greater visibility (protected can become public, not private).
4. Overriding Final Methods
Declaring a method final prevents overriding. Attempting to override causes a fatal error.
5. Confusing extends and implements
extends is for class inheritance (one parent). implements is for interfaces (multiple allowed).
Practice Questions
1. What keyword is used for inheritance?
The extends keyword. class Child extends Parent inherits all public and protected members.
2. How do you call a parent constructor from a child?
Use parent::__construct() inside the child's __construct method.
3. What is an abstract class?
A class that cannot be instantiated directly. It may contain abstract methods that must be implemented by child classes.
4. What does the final keyword do?
Prevents a method from being overridden or a class from being extended.
5. Challenge: Create a shape hierarchy with abstract base class and area calculation.
<?php
abstract class Shape {
abstract public function getArea(): float;
}
class Circle extends Shape {
public function __construct(private float $radius) {}
public function getArea(): float {
return pi() * $this->radius ** 2;
}
}
class Rectangle extends Shape {
public function __construct(private float $width, private float $height) {}
public function getArea(): float {
return $this->width * $this->height;
}
}
$shapes = [new Circle(5), new Rectangle(4, 6)];
foreach ($shapes as $shape) echo $shape->getArea() . "\n";
FAQ
Mini Project: Employee Hierarchy
Build an employee management hierarchy using inheritance.
<?php
abstract class Employee {
public function __construct(
protected string $name,
protected float $baseSalary
) {}
abstract public function calculateSalary(): float;
}
class Developer extends Employee {
public function calculateSalary(): float {
return $this->baseSalary + 5000; // Bonus
}
}
class Manager extends Employee {
public function __construct(
string $name,
float $baseSalary,
private array $teamMembers = []
) { parent::__construct($name, $baseSalary); }
public function calculateSalary(): float {
return $this->baseSalary + count($this->teamMembers) * 2000;
}
}
echo (new Developer("Alice", 60000))->calculateSalary(); // 65000
echo (new Manager("Bob", 80000, ["Charlie", "Diana"]))->calculateSalary(); // 84000
What's Next
PHP Interfaces PHP Traits PHP Namespaces
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro