Inheritance
suggest changeInheritance lets a class reuse and extend another class. You write class Dog extends Animal, and Dog (the child or subclass) gets all the public and protected methods, properties and constants of Animal (the parent or base class). The child can add new members and can replace inherited methods with its own versions.
A child object is a parent object: a Dog can be passed anywhere an Animal is expected. That is what makes inheritance useful, and it's also why it should be used with care.
This article covers:
extendsand what a child class inherits- how
public,protectedandprivatebehave across the hierarchy - the "is a" relationship:
instanceofand type declarations - constructors in child classes
- inspecting a class hierarchy at run time
- single inheritance, and combining it with interfaces and traits
- abstract base classes
- static properties and the
staticreturn type final, readonly and enum classes, which restrict inheritance- building exception hierarchies
Replacing inherited methods is covered in detail in Overriding. When inheritance isn't the right tool, see Composition and delegation. Other related topics: Abstract Classes, Interfaces, Traits and Final Keyword.
extends: the basics
<?php
class Animal
{
public string $name;
protected int $legs = 4;
public function __construct(string $name)
{
$this->name = $name;
}
public function describe(): string
{
return "{$this->name} has {$this->legs} legs";
}
public function speak(): string
{
return '...';
}
}
class Dog extends Animal
{
public function fetch(): string
{
return "{$this->name} fetches the ball";
}
public function speak(): string
{
return 'Woof';
}
}
class Bird extends Animal
{
protected int $legs = 2;
public function fly(): string
{
return "{$this->name} flies away";
}
}
$dog = new Dog('Rex');
echo $dog->describe(), "\n"; // inherited from Animal
echo $dog->speak(), "\n"; // overridden in Dog
echo $dog->fetch(), "\n"; // new in Dog
$bird = new Bird('Tweety');
echo $bird->describe(), "\n"; // inherited, but sees Bird's $legs
echo $bird->speak(), "\n"; // inherited unchanged
echo $bird->fly(), "\n";
Output:
Rex has 4 legs
Woof
Rex fetches the ball
Tweety has 2 legs
...
Tweety flies away
A child class can do three things with what it inherits:
- use it unchanged:
Birdinheritsspeak()and the constructor - add to it:
Dog::fetch()andBird::fly()exist only in the child - replace it:
Dog::speak()overridesAnimal::speak(), andBirdredeclares$legswith a different default
describe() is written once in Animal, but $this inside it is the actual object, so it reads Bird's $legs. The rules for replacing methods (compatible signatures, parent::, #[\Override]) are in Overriding.
What a child can access
Visibility decides what the child class can see:
publicmembers are visible everywhere, including the child.protectedmembers are visible inside the class and its children, but not from outside code. This is the visibility for things meant to be used or customized by subclasses.privatemembers are visible only inside the class that declares them. They still exist in a child object, but the child's code can't touch them.
<?php
class Account
{
public string $owner;
protected int $balance = 0;
private array $log = [];
public function __construct(string $owner)
{
$this->owner = $owner;
}
public function deposit(int $amount): void
{
$this->balance += $amount;
$this->log[] = "deposit $amount";
}
public function history(): array
{
return $this->log;
}
}
class SavingsAccount extends Account
{
public function addInterest(float $rate): void
{
// protected: accessible in the child
$this->balance += (int) round($this->balance * $rate);
}
public function balance(): int
{
return $this->balance;
}
public function peekLog(): mixed
{
// private to Account: not visible here
return $this->log;
}
}
$s = new SavingsAccount('Ada');
$s->deposit(1000);
$s->addInterest(0.05);
echo $s->owner, ": ", $s->balance(), "\n";
print_r($s->history()); // Account's own method can read its private $log
var_dump($s->peekLog());
Output:
Ada: 1050
Array
(
[0] => deposit 1000
)
Warning: Undefined property: SavingsAccount::$log in ... on line 41
NULL
The $log array is there (the inherited history() method reads it fine), but from SavingsAccount's code it looks like the property doesn't exist.
Because private members are invisible to children, a child can declare a private property with the same name. It doesn't replace the parent's property; the object ends up with two separate properties:
<?php
class Base
{
private string $secret = 'base secret';
public function baseSecret(): string
{
return $this->secret;
}
}
class Child extends Base
{
// a separate property that happens to have the same name
private string $secret = 'child secret';
public function childSecret(): string
{
return $this->secret;
}
}
$c = new Child();
echo $c->baseSecret(), "\n";
echo $c->childSecret(), "\n";
var_dump($c);
Output:
base secret
child secret
object(Child)#1 (2) {
["secret":"Base":private]=>
string(11) "base secret"
["secret":"Child":private]=>
string(12) "child secret"
}
This is a good thing: a parent class can rename or add private members without breaking subclasses. Keep members private by default and make them protected only when subclasses really need them. More in Method and Property Visibility.
The "is a" relationship
An instance of a child class is also an instance of every class above it. instanceof checks this, and parameter, property and return types accept subclasses:
<?php
class Shape
{
public function area(): float
{
return 0.0;
}
}
class Rectangle extends Shape
{
public function __construct(protected float $w, protected float $h) {}
public function area(): float
{
return $this->w * $this->h;
}
}
class Square extends Rectangle
{
public function __construct(float $side)
{
parent::__construct($side, $side);
}
}
function totalArea(Shape ...$shapes): float
{
return array_sum(array_map(fn(Shape $s) => $s->area(), $shapes));
}
$sq = new Square(3);
var_dump($sq instanceof Square);
var_dump($sq instanceof Rectangle);
var_dump($sq instanceof Shape);
var_dump(new Shape() instanceof Rectangle);
echo totalArea(new Rectangle(2, 5), $sq, new Shape()), "\n";
Output:
bool(true)
bool(true)
bool(true)
bool(false)
19
totalArea() only knows about Shape, yet it works with every subclass, and each object computes its own area. Writing code against a base type and letting subclasses supply the behavior is called polymorphism.
For this to work, a subclass must honor the parent's contract: anything that is valid for a Shape must be valid for a Square (the Liskov substitution principle). PHP enforces the method signature part of that contract, as described in Overriding. It can't enforce the behavior. The classic example: if Rectangle had setWidth() and setHeight(), a Square subclass would have to change both dimensions in each, surprising code that expects a rectangle's width to change independently. If a child can't honestly do everything the parent promises, it shouldn't be a child. See also instanceof type operator.
Constructors
Constructors are inherited like other methods. If the child doesn't define one, the parent's constructor is used. If the child defines its own, the parent's constructor is not called automatically; call it with parent::__construct():
<?php
class Model
{
public function __construct(protected array $attributes = [])
{
echo static::class, " created via Model::__construct\n";
}
}
// no constructor: Model's constructor is inherited
class Post extends Model {}
// own constructor: must call the parent's explicitly
class User extends Model
{
public function __construct(public readonly string $email, array $attributes = [])
{
parent::__construct($attributes + ['role' => 'member']);
}
public function role(): string
{
return $this->attributes['role'];
}
}
$p = new Post(['title' => 'Hello']);
$u = new User('ada@example.com');
echo $u->email, " is a ", $u->role(), "\n";
Output:
Post created via Model::__construct
User created via Model::__construct
ada@example.com is a member
Notes:
- A child constructor may have a completely different signature from the parent's. The usual signature compatibility rules don't apply to constructors.
- Constructor property promotion works in child constructors. Promote only the child's new properties and pass the rest to
parent::__construct(). Don't re-promote a property the parent already declares. static::classin the parent constructor is the class actually being created.
Forgetting parent::__construct() is a common bug: the parent's properties stay uninitialized. See Calling a parent constructor when instantiating a child.
Inspecting the hierarchy
PHP has functions to find out how classes are related at run time. They accept an object or a class name:
<?php
class Vehicle {}
class Car extends Vehicle {}
class ElectricCar extends Car {}
class Bike extends Vehicle {}
$tesla = new ElectricCar();
var_dump(get_parent_class($tesla));
var_dump(get_parent_class('Car'));
var_dump(get_parent_class(new Vehicle()));
print_r(class_parents($tesla));
var_dump(is_subclass_of($tesla, 'Vehicle'));
var_dump(is_subclass_of($tesla, 'ElectricCar')); // not a subclass of itself
var_dump(is_a($tesla, 'ElectricCar')); // but it is one
var_dump(is_a('Bike', 'Vehicle', allow_string: true));
var_dump(is_subclass_of('Bike', 'Car'));
// walk the chain with reflection
$r = new ReflectionClass($tesla);
$chain = [];
do {
$chain[] = $r->getName();
} while ($r = $r->getParentClass());
echo implode(' -> ', $chain), "\n";
Output:
string(3) "Car"
string(7) "Vehicle"
bool(false)
Array
(
[Car] => Car
[Vehicle] => Vehicle
)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
ElectricCar -> Car -> Vehicle
get_parent_class()returns the direct parent, orfalsefor a class without one.class_parents()returns all ancestors, nearest first.is_subclass_of()is true only for strict descendants.is_a()andinstanceofalso match the class itself.is_a()needsallow_string: trueto accept a class name as the first argument.
In ordinary code, instanceof is all you need. The other functions are mostly useful in frameworks, serializers and debugging tools.
Single inheritance, interfaces and traits
A PHP class can extend only one class:
<?php
class Reader {}
class Writer {}
class Stream extends Reader, Writer {}
Output:
Parse error: syntax error, unexpected token ",", expecting "{" in ... on line 5
To give a class several types, use interfaces: a class can implement any number of them, and an interface can extend several other interfaces. To share code across unrelated classes, use traits. A class can combine one parent, many interfaces and many traits:
<?php
interface Readable
{
public function read(): string;
}
interface Writable
{
public function write(string $data): void;
}
// an interface may extend several interfaces
interface ReadWritable extends Readable, Writable {}
trait CountsBytes
{
private int $bytes = 0;
public function bytes(): int
{
return $this->bytes;
}
}
abstract class Resource
{
public function __construct(public readonly string $name) {}
}
// one parent class, any number of interfaces and traits
class MemoryStream extends Resource implements ReadWritable
{
use CountsBytes;
private string $buffer = '';
public function read(): string
{
return $this->buffer;
}
public function write(string $data): void
{
$this->buffer .= $data;
$this->bytes += strlen($data);
}
}
$m = new MemoryStream('mem');
$m->write('hello ');
$m->write('world');
echo $m->read(), " (", $m->bytes(), " bytes)\n";
var_dump($m instanceof Resource, $m instanceof Readable, $m instanceof ReadWritable);
print_r(class_implements($m));
print_r(class_uses($m));
Output:
hello world (11 bytes)
bool(true)
bool(true)
bool(true)
Array
(
[ReadWritable] => ReadWritable
[Writable] => Writable
[Readable] => Readable
)
Array
(
[CountsBytes] => CountsBytes
)
Interfaces are inherited too: a subclass of MemoryStream would automatically implement ReadWritable. Note that class_uses() lists only traits used directly by the class, not those used by its parents. See Interfaces and Traits.
Abstract base classes
Often the base class isn't meant to be used on its own. It provides shared code and leaves some steps to subclasses. Declare it abstract: it can't be instantiated, and its abstract methods must be implemented by every concrete child:
<?php
abstract class Notification
{
public function __construct(protected string $recipient) {}
// every subclass must provide these
abstract protected function channel(): string;
abstract protected function body(): string;
// shared behavior, written once
public function send(): string
{
return sprintf('[%s] to %s: %s', $this->channel(), $this->recipient, $this->body());
}
}
class WelcomeEmail extends Notification
{
protected function channel(): string { return 'email'; }
protected function body(): string { return 'Welcome aboard!'; }
}
class LoginSms extends Notification
{
public function __construct(string $phone, private string $code)
{
parent::__construct($phone);
}
protected function channel(): string { return 'sms'; }
protected function body(): string { return "Your code is {$this->code}"; }
}
echo (new WelcomeEmail('ada@example.com'))->send(), "\n";
echo (new LoginSms('+15550100', '4821'))->send(), "\n";
try {
new Notification('x');
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
Output:
[email] to ada@example.com: Welcome aboard!
[sms] to +15550100: Your code is 4821
Error: Cannot instantiate abstract class Notification
This is the template method pattern, and it's the healthiest form of inheritance: the parent was designed to be extended, and the extension points (channel() and body()) are explicit. Details in Abstract Classes.
Static properties are shared
A static property belongs to the class where it is declared. A subclass that doesn't redeclare it shares the same storage with the parent. Redeclaring it gives the subclass its own copy:
<?php
class Counter
{
public static int $count = 0;
public static function increment(): void
{
static::$count++;
}
}
class PageCounter extends Counter {}
class ClickCounter extends Counter
{
// redeclared: ClickCounter gets its own storage
public static int $count = 0;
}
Counter::increment();
PageCounter::increment();
PageCounter::increment();
ClickCounter::increment();
echo "Counter: ", Counter::$count, "\n";
echo "PageCounter: ", PageCounter::$count, "\n";
echo "ClickCounter: ", ClickCounter::$count, "\n";
Output:
Counter: 3
PageCounter: 3
ClickCounter: 1
Counter::$count and PageCounter::$count are the same variable. This catches people who keep a per-class registry or cache in a static property on a base class: all subclasses write into one array unless each redeclares the property (or the array is keyed by static::class). Note also the use of static:: instead of self::; with self::$count, ClickCounter::increment() would have incremented Counter's copy. See Late static binding.
The static return type
Methods that return $this or create a new instance should declare the static return type. It means "the class the method was called on", so fluent calls keep the subclass type:
<?php
class QueryBuilder
{
protected array $parts = [];
public static function create(): static
{
return new static();
}
public function where(string $cond): static
{
$this->parts[] = "WHERE $cond";
return $this;
}
public function sql(): string
{
return implode(' ', $this->parts);
}
}
class MysqlQueryBuilder extends QueryBuilder
{
public function limit(int $n): static
{
$this->parts[] = "LIMIT $n";
return $this;
}
}
$q = MysqlQueryBuilder::create() // static: returns a MysqlQueryBuilder
->where('id > 10') // still a MysqlQueryBuilder
->limit(5); // so limit() is available
echo get_class($q), "\n";
echo $q->sql(), "\n";
Output:
MysqlQueryBuilder
WHERE id > 10 LIMIT 5
new static() creates an instance of the called class. With new self(), MysqlQueryBuilder::create() would return a plain QueryBuilder, and calling limit() on it would fail. A return type of self on where() would still run, but IDEs and static analyzers would believe the result is a QueryBuilder and flag ->limit(5) as an error.
Restricting inheritance
Some classes can't be extended.
A final class can't have children:
<?php
final class Money
{
public function __construct(public readonly int $cents) {}
}
class FakeMoney extends Money {}
Output:
Fatal error: Class FakeMoney cannot extend final class Money in ... on line 7
Stack trace:
#0 {main}
A readonly class (PHP 8.2+) can only be extended by another readonly class, so a subclass can't sneak mutable state into an immutable type:
<?php
readonly class Point
{
public function __construct(public int $x, public int $y) {}
}
class MutablePoint extends Point {}
Output:
Fatal error: Non-readonly class MutablePoint cannot extend readonly class Point in ... on line 7
Stack trace:
#0 {main}
Declaring the child as readonly class Point3D extends Point works. See Immutability.
Enums are implicitly final. They can implement interfaces and use traits, but they can't extend or be extended:
<?php
enum Status
{
case Active;
}
class MoreStatus extends Status {}
Output:
Fatal error: Class MoreStatus cannot extend enum Status in ... on line 7
Stack trace:
#0 {main}
(The Stack trace lines are printed for fatal errors since PHP 8.5.)
Making your own classes final by default is a widely followed practice. It keeps you free to change the class's internals, and anyone who needs different behavior can wrap it, as shown in Composition and delegation. Remove final deliberately when you design a class for extension. Individual methods and constants can also be final; see Final Keyword.
Extending built-in classes: exception hierarchies
The most common place where application code uses inheritance is exceptions. Every exception class extends Exception (or Error), and catch matches subclasses, so a hierarchy of exception classes lets callers choose how specific to be:
<?php
// base exception for one library
class PaymentException extends RuntimeException {}
class CardDeclinedException extends PaymentException
{
public function __construct(public readonly string $reason)
{
parent::__construct("Card declined: $reason", code: 402);
}
}
class GatewayTimeoutException extends PaymentException {}
function charge(int $cents): void
{
match (true) {
$cents > 10_000 => throw new CardDeclinedException('limit exceeded'),
$cents < 0 => throw new InvalidArgumentException('negative amount'),
$cents === 0 => throw new GatewayTimeoutException('gateway did not respond'),
default => print("charged $cents\n"),
};
}
foreach ([500, 20_000, 0, -1] as $amount) {
try {
charge($amount);
} catch (CardDeclinedException $e) {
// most specific first
echo "declined ({$e->reason}), code {$e->getCode()}\n";
} catch (PaymentException $e) {
// any other payment problem
echo get_class($e), ": ", $e->getMessage(), "\n";
} catch (Exception $e) {
echo "other: ", $e->getMessage(), "\n";
}
}
print_r(class_parents(new CardDeclinedException('x')));
Output:
charged 500
declined (limit exceeded), code 402
GatewayTimeoutException: gateway did not respond
other: negative amount
Array
(
[PaymentException] => PaymentException
[RuntimeException] => RuntimeException
[Exception] => Exception
)
Tips:
- Give each library or module one base exception class, so callers can catch everything it throws with a single
catch. - Extend the SPL exception that best describes the problem (
RuntimeException,InvalidArgumentException,LogicException, ...), so generic handlers still work. - Order
catchblocks from most to least specific. The first matching block wins, socatch (PaymentException $e)placed first would also catchCardDeclinedException. - When the child adds a constructor, pass the message and code on with
parent::__construct().
See Exception Handling and Error Reporting.
When to use inheritance
Inheritance creates the tightest coupling there is between two classes: the child depends on the parent's public API, its protected members and often on how its methods call each other internally. A change in the parent can break every subclass. This is known as the fragile base class problem, demonstrated in Composition and delegation.
Inheritance is a good fit when:
- the relationship is a genuine, stable "is a":
CardDeclinedExceptionis aPaymentException - the parent is designed for extension, typically an abstract class with explicit
protectedorabstractextension points - a framework expects it, such as extending a base controller, test case or ORM model
Prefer something else when:
- you only want to reuse some code: use a trait or composition
- you want several types for one class: use interfaces
- the child would need to disable or weaken inherited behavior (throwing "not supported" from an override is a sign the hierarchy is wrong)
- the hierarchy grows deeper than two or three levels
Summary
class Child extends Parentinherits all public and protected members. The child can use them, add new ones and override methods.privatemembers exist in child objects but are invisible to the child's code; a same-named private member in the child is a separate member.- A child object is an instance of all its ancestors and is accepted wherever they are. Subclasses must keep the parent's promises.
- If a child defines a constructor, call
parent::__construct()yourself. - Use
get_parent_class(),class_parents(),is_subclass_of()andis_a()to inspect hierarchies. - A class has exactly one parent but any number of interfaces and traits.
- Abstract classes define shared code plus explicit extension points.
- Static properties are shared with subclasses unless redeclared. Use
static::and thestaticreturn type so subclasses work correctly. finalclasses, enums and (for non-readonly children) readonly classes can't be extended. Make classesfinalunless they're designed for extension.- Exception hierarchies are the most common, and most appropriate, use of inheritance in everyday PHP.