bhylu.com

Advertisements

PHP Inheritance

Inheritance lets a subtype provide behaviour through a parent contract. Use it for a meaningful substitutability relationship rather than merely to share a few lines of code.

How it works

A child can override a suitable method while retaining the parent’s contract. parent:: can call the inherited implementation. Keep visibility and parameter/result compatibility in mind when overriding. If two classes only need a shared formatter or sender, composition may express the relationship better. final can deliberately prevent extension of a class or method whose invariants would otherwise be fragile.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l inheritance.php
php inheritance.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · inheritance.php

<?php
declare(strict_types=1);

class Receipt {
    public function heading(): string { return "Loan receipt"; }
}
class ReturnReceipt extends Receipt {
    public function heading(): string { return parent::heading() . " — returned"; }
}
function printHeading(Receipt $receipt): void { echo $receipt->heading(), "\n"; }
printHeading(new ReturnReceipt());

Expected result

Loan receipt — returned

The function accepts the parent type but receives the child’s behaviour. The override preserves the return type and uses the parent’s heading as one building block. A real receipt model should also state whether all parent operations remain meaningful for a return receipt; the inheritance syntax does not prove that design claim.

Check the official PHP manual for detailed version and API contracts.