Inheritance in PHP
| Introduction | |
| extends and method overriding | |
| parent:: and constructors | |
| Abstract classes and final | |
| One parent only |
Introduction
Inheritance lets a child class reuse and specialize a parent (base) class: the child gets every public and protected member for free and overrides only what differs. Basics first — OOP in PHP.
extends and method overriding
<?php
namespace Aredel\Demo;
class Page
{
public function render(): string
{
return 'base';
}
}
class ArticlePage extends Page
{
public function render(): string
{
return 'article: ' . parent::render();
}
}
The child inherits everything non-private and may override any method with a compatible signature (same or wider visibility, compatible types — PHP enforces this).
parent:: and constructors
Constructors are not chained automatically: if the child defines __construct(), the parent one never runs unless the child calls parent::__construct() explicitly. Forgetting that call is the classic inheritance bug — mandatory parent setup silently skipped. Rule: a child constructor either calls the parent one first or documents why it must not.
Abstract classes and final
abstract class cannot be instantiated — it exists only to be extended, and its abstract methods force every child to implement them (a contract with shared code attached). final is the opposite lock: a final class cannot be extended, a final method cannot be overridden. Abstract for frameworks, final for value objects and security-sensitive code.
One parent only
PHP allows exactly one parent per class — class D extends B, C is a fatal error. When one class needs behavior from two sibling branches at once, the answer is traits (or composition).
Article author: Arthur Isaev
| Development with PHP | |
| OOP in PHP | |
| PHP 8 Classes | |
| Inheritance in PHP | |
| Methods from two sibling classes: traits |