The Analogy: The Master Blueprint and Its Revisions
An architecture firm keeps a master blueprint for a standard two-storey house: foundations, load-bearing walls, roof pitch, the things every build shares. When a client wants a variant -- a garage on the side, a bigger kitchen -- the firm does not redraw the whole house. They take a copy of the master, stamp "based on Standard Type A" across the top, and draw only the changes on transparent overlays. The garage variant is the master plus its overlay; the coastal variant is the master plus a different overlay. Every variant automatically inherits the foundations and the roof, because those live on the master sheet that all of them are built over.
That is inheritance. A base class holds what every variant shares; a subclass declared with extends is the overlay, adding or changing only what makes it different. A Manager is an Employee with a bonus overlay; it does not restate what an employee is, it inherits it. When the subclass needs to build on the base rather than replace it, it calls up to the master sheet with parent:: -- the way the garage overlay still references "see foundations on master sheet" rather than redrawing them. This is code reuse by specialisation: write the common part once, vary only the difference.
Some master sheets, though, are deliberately incomplete. The firm keeps a "generic detached dwelling" template that fixes the shared structure but leaves the floor plan as a blank rectangle stamped "each build must supply its own layout". Nobody can build directly from that template -- it is not a real house until someone draws the floor plan. That is an abstract class: it defines shared behaviour but marks certain methods abstract, meaning "every concrete subclass must supply this". You cannot instantiate it directly; it exists only to be extended, guaranteeing that whatever a subclass looks like, it will at least answer the methods the base declared.
The failure mode is the overlay that quietly contradicts the master. Suppose a variant's overlay widens a doorway that the master marked load-bearing, and the builder, trusting the master's structural notes, never rechecks it -- the wall comes down. In code this is a subclass that overrides a method but breaks the promise the base made about it: the base said "this always returns a positive price", the subclass returns a negative one, and every piece of code written against the base is now wrong when handed the subclass. Inheritance hands you the base's trust for free, which means a careless override betrays not one call site but every place that relied on the base's contract. Subclasses must honour what they inherit, not just reuse it.
Syntax or Core Structure
A subclass uses extends to inherit a base class's properties and methods. It can override a method by redeclaring it, and reach the base version with parent::. Members marked protected are visible to the class and its subclasses but not to outside code.
<?php
declare(strict_types=1);
class Animal {
public function __construct(protected string $name) {}
public function speak(): string {
return "{$this->name} makes a sound";
}
}
class Dog extends Animal {
public function speak(): string {
return parent::speak() . ", specifically a Woof";
}
}
echo (new Animal('Generic'))->speak(), "\n";
echo (new Dog('Rex'))->speak(), "\n";
Output:
Generic makes a sound
Rex makes a sound, specifically a Woof
Dog inherits the $name property and the speak method from Animal, then overrides speak to extend it. The call to parent::speak() runs the base version first -- producing Rex makes a sound -- and the override appends to it. $name is protected, so Dog can read it through the inherited constructor, but code outside the hierarchy still cannot touch it. Overriding by building on parent:: rather than replacing wholesale is the safe pattern: the subclass specialises the base's behaviour instead of discarding it.
Technical Depth: Abstract Classes and What Subclasses Inherit
Concrete versus abstract
A class is either concrete (fully defined, can be instantiated) or abstract (partly defined, exists only to be extended). The table contrasts the two.
| Aspect | Concrete class | Abstract class |
|---|---|---|
Can you write new on it | Yes | No -- fatal error |
| Can it hold implemented methods | Yes | Yes, shared by subclasses |
| Can it declare unimplemented methods | No | Yes, with abstract |
| Purpose | A usable thing | A contract plus shared behaviour |
An abstract method is a signature with no body, marked abstract; any concrete subclass must implement it or the subclass is itself abstract. This is how a base class forces its descendants to fill in the parts that only they can define, while still providing the shared logic that wraps around them.
An abstract base with a template method
Here Shape implements describe() once but leaves area() abstract, so each shape supplies its own area while sharing the description logic. static::class yields the name of the actual subclass at runtime.
<?php
declare(strict_types=1);
abstract class Shape {
abstract public function area(): int;
public function describe(): string {
return static::class . " area = " . $this->area();
}
}
class Square extends Shape {
public function __construct(private int $side) {}
public function area(): int { return $this->side ** 2; }
}
class Rectangle extends Shape {
public function __construct(private int $w, private int $h) {}
public function area(): int { return $this->w * $this->h; }
}
echo (new Square(4))->describe(), "\n";
echo (new Rectangle(3, 4))->describe(), "\n";
Output:
Square area = 16
Rectangle area = 12
Neither subclass rewrites describe(); they inherit it and supply only the area() it depends on. Writing new Shape() would be a fatal error because Shape is abstract, which is exactly the guarantee you want: there is no such thing as a generic shape with no area. The describe() method is a template method -- fixed shared logic that calls down to the abstract hook each subclass fills in -- and static::class reports Square or Rectangle rather than Shape because it resolves to the class of the actual instance at runtime.
Sealing a method with final
Inheritance is powerful, but sometimes a base class needs to guarantee that a particular method can never be overridden -- because its correctness depends on running exactly as written. The final keyword enforces that: a final method cannot be overridden, and a final class cannot be extended at all.
<?php
declare(strict_types=1);
class Ledger {
final public function postingId(int $seq): string {
return 'POST-' . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
}
public function label(): string { return 'ledger'; }
}
class AuditLedger extends Ledger {
public function label(): string { return 'audit'; } // fine: not final
}
$a = new AuditLedger();
echo $a->postingId(7), "\n";
echo $a->label(), "\n";
Output:
POST-0007
audit
AuditLedger freely overrides label(), but any attempt to override postingId() would be a compile-time fatal error, because the base sealed it with final. The subclass still inherits and uses the final method -- postingId(7) yields POST-0007 -- it simply cannot change it. Use final sparingly and deliberately: it is the right tool when an override would violate an invariant (an id format, a security check), but overusing it makes a class hard to adapt and test.
Real World Example: A Payroll Hierarchy
Payroll is a textbook case for inheritance: every employee has a name and a monthly pay, but the way pay is computed differs by kind. An abstract Employee fixes the shared shape and declares monthlyPayCents() abstract; each subclass implements it. A Manager extends Salaried and reuses its calculation via parent::, adding a bonus. The payroll loop treats them all uniformly -- it just asks each for its pay.
<?php
declare(strict_types=1);
abstract class Employee {
public function __construct(public readonly string $name) {}
abstract public function monthlyPayCents(): int;
abstract public function kind(): string;
}
class Salaried extends Employee {
public function __construct(string $name, protected int $baseCents) {
parent::__construct($name);
}
public function monthlyPayCents(): int { return $this->baseCents; }
public function kind(): string { return 'Salaried'; }
}
class Hourly extends Employee {
public function __construct(string $name, private int $rateCents, private int $hours) {
parent::__construct($name);
}
public function monthlyPayCents(): int { return $this->rateCents * $this->hours; }
public function kind(): string { return 'Hourly'; }
}
class Manager extends Salaried {
public function __construct(string $name, int $baseCents, private int $bonusCents) {
parent::__construct($name, $baseCents);
}
public function monthlyPayCents(): int { return parent::monthlyPayCents() + $this->bonusCents; }
public function kind(): string { return 'Manager'; }
}
$staff = [
new Salaried('Ada', 500000),
new Hourly('Ben', 8000, 40),
new Manager('Cara', 500000, 150000),
];
echo "PAYROLL\n";
echo str_repeat('-', 7), "\n";
$total = 0;
foreach ($staff as $e) {
$total += $e->monthlyPayCents();
printf("%-6s %-9s %10s\n", $e->name, $e->kind(), number_format($e->monthlyPayCents() / 100, 2));
}
printf("%-6s %-9s %10s\n", 'TOTAL', '', number_format($total / 100, 2));
Output:
PAYROLL
-------
Ada Salaried 5,000.00
Ben Hourly 3,200.00
Cara Manager 6,500.00
TOTAL 14,700.00
The loop is fully polymorphic: it never checks what kind of employee it holds, it just calls monthlyPayCents() and lets each class answer for itself. Salaried returns its base, Hourly multiplies rate by hours (8000 cents times 40 gives 3,200.00), and Manager reuses Salaried's base through parent::monthlyPayCents() and adds its bonus to reach 6,500.00. The comma in number_format's output is worth noting -- it groups thousands by default, so 14,700.00 is the real formatting, not 14700.00.
The hierarchy is clean, but Manager extends Salaried embeds a real design assumption that will eventually break: it hard-codes that a manager is always paid like a salaried employee plus a bonus. The day the business wants an hourly manager, or a manager whose bonus is a percentage of the team's output, the inheritance chain fights back -- you cannot be both Hourly and Manager because PHP has single inheritance, and Manager's parent:: is welded to Salaried. This is the classic "prefer composition over inheritance" lesson: deep extends chains model "is-a-kind-of" rigidly, and real business rules are rarely that tidy. A more flexible design would compose a pay-calculation strategy into Employee rather than encoding each pay rule as a subclass.
Common Mistakes
- Overriding a method and breaking its contract. If the base promises a non-negative result or a certain type, a subclass override must honour that promise. Violating it means every caller written against the base is wrong when handed the subclass.
- Forgetting to call
parent::__construct. When a subclass declares its own constructor, the parent's constructor does not run automatically. Omitting theparent::call leaves inherited properties uninitialised.
- Trying to instantiate an abstract class.
newon an abstract class is a fatal error. Abstract classes exist only to be extended; if you need an instance, you need a concrete subclass.
- Reaching for deep inheritance where composition fits. Modelling every variation as another
extendsproduces rigid, tangled hierarchies. When behaviour varies independently along several axes, compose collaborators instead of subclassing.
- Making base properties
privatewhen subclasses need them. Aprivateproperty is invisible even to subclasses. If a subclass legitimately needs access, useprotected; if nothing outside the class does, keep it private.
- Confusing
self::withstatic::.self::binds to the class where the code is written;static::binds to the runtime class of the instance. Usingself::where you meantstatic::breaks overriding in subclasses.
- Widening a parameter type or narrowing a return type in an override. PHP enforces variance rules; an override may accept broader parameters and return narrower types, but the reverse is an error. Match the base signature unless you understand the variance you are using.
- Duplicating shared logic across sibling subclasses. If two subclasses copy the same method, that logic belongs in the base class. Inheritance is meant to eliminate exactly that duplication.
- Relying on the base class's internals from a subclass. A subclass that reaches into how the base stores its state, rather than using its protected methods, breaks the moment the base's implementation changes. Depend on the base's interface, not its guts.
Best Practices
- Use inheritance only for a genuine "is-a" relationship where the subclass can stand in for the base everywhere the base is expected.
- Build on inherited behaviour with
parent::rather than copying or wholesale-replacing it, so shared logic stays in one place.
- Make abstract any base class that has no meaningful standalone instance, and declare as
abstractthe methods each subclass must supply.
- Prefer
protectedoverprivateonly when a subclass truly needs the member; default toprivateto keep the base's internals free to change.
- Reach for composition -- injecting a collaborator -- when behaviours vary independently, reserving inheritance for stable, shallow hierarchies.
- Use
static::(late static binding) when a base method must refer to the runtime subclass; useself::only when you deliberately mean the defining class.
- Keep override signatures compatible with the base, honouring PHP's variance rules so subclasses remain safe substitutes.
- Document the contract a base method promises, so subclass authors know what an override must preserve.
Practice Exercises
- Define an abstract
Notificationclass with an abstractsend(string $message): stringmethod and a concreteformat()helper. ImplementEmailNotificationandSmsNotification, and loop over a mixed array callingsendpolymorphically.
- Build a
Vehiclebase class with adescribe()template method that calls an abstractwheels(): int. ImplementCarandMotorcycle, and show thatnew Vehicle()is rejected.
- Take the payroll example and add a
Contractorsubclass whose pay is a day rate times days worked. Add it to the staff array and confirm the total updates without changing the loop.
- Demonstrate the
self::versusstatic::difference: write a base class with a staticcreate()that returnsnew static(), subclass it, and show that the subclass'screate()returns an instance of the subclass, not the base.