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
Изображение баннера

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: