Overriding
suggest changeA child class overrides an inherited method by declaring a method with the same name. When the method is called on a child object, PHP runs the child's version, even if the call comes from code in the parent class. This is the main way to customize inherited behavior.
This article covers:
- how overriding works and how to call the parent's version with
parent:: - the signature rules PHP enforces (parameters, return types, visibility)
- the
#[\Override]attribute (PHP 8.3+) andfinal - overriding constructors, static methods, constants and properties
- how traits fit in, and common pitfalls
Related topics: Abstract Classes, Interfaces, Final Keyword, Late static binding and Dynamic Binding.
Basic overriding
<?php
class Shape
{
public function name(): string
{
return 'shape';
}
public function area(): float
{
return 0.0;
}
public function describe(): string
{
return sprintf('%s with area %.2f', $this->name(), $this->area());
}
}
class Circle extends Shape
{
public function __construct(private float $r) {}
public function name(): string
{
return 'circle';
}
public function area(): float
{
return M_PI * $this->r ** 2;
}
}
class Square extends Shape
{
public function __construct(private float $side) {}
public function area(): float
{
return $this->side ** 2;
}
}
$shapes = [new Shape(), new Circle(1.5), new Square(3)];
foreach ($shapes as $s) {
echo $s->describe(), "\n";
}
Output:
shape with area 0.00
circle with area 7.07
shape with area 9.00
describe() exists only in Shape, but $this->name() and $this->area() are resolved at run time from the actual class of the object. Circle overrides both methods. Square overrides only area(), so it inherits name() from Shape.
Calling the parent method with parent::
An override replaces the parent method completely. To extend the parent's behavior rather than replace it, call it with parent::method():
<?php
class Logger
{
public function format(string $msg): string
{
return "log: $msg";
}
}
class PrefixLogger extends Logger
{
public function __construct(private string $prefix) {}
public function format(string $msg): string
{
// reuse the parent's formatting, then add to it
return '[' . $this->prefix . '] ' . parent::format($msg);
}
}
class LoudLogger extends PrefixLogger
{
public function format(string $msg): string
{
return strtoupper(parent::format($msg)) . '!';
}
}
echo (new Logger())->format('started'), "\n";
echo (new PrefixLogger('db'))->format('connected'), "\n";
echo (new LoudLogger('db'))->format('connected'), "\n";
Output:
log: started
[db] log: connected
[DB] LOG: CONNECTED!
parent:: refers to the direct parent class. In LoudLogger, parent::format() calls PrefixLogger::format(), which in turn calls Logger::format(). The call still runs on the same object, so $this inside the parent method is the child object.
Signature compatibility
PHP checks that an overriding method can be used anywhere the parent method can (the Liskov substitution principle). Code written against the parent class must keep working when given a child object. The rules:
- Return types may be narrowed (covariance): if the parent returns
Animal, the child may returnDog. - Parameter types may be widened (contravariance): if the parent accepts
DogFood, the child may acceptFood. - Extra parameters are allowed only if they are optional.
- Required parameters can't be removed or made required where the parent had them optional.
- A method that is static in the parent must be static in the child, and vice versa.
<?php
class Animal {}
class Dog extends Animal {}
class Food {}
class DogFood extends Food {}
class Shelter
{
public function adopt(string $name): Animal
{
return new Animal();
}
public function feed(DogFood $food): void {}
}
class DogShelter extends Shelter
{
// return type narrowed: Dog is an Animal (covariance)
// extra parameter is fine because it is optional
public function adopt(string $name, bool $vaccinated = true): Dog
{
return new Dog();
}
// parameter type widened: accepts any Food (contravariance)
public function feed(Food $food): void {}
}
$s = new DogShelter();
echo get_class($s->adopt('Rex')), "\n";
$s->feed(new Food());
echo "ok\n";
Output:
Dog
ok
Violations are detected when the class is declared, as a fatal error. Widening a return type is not allowed, because callers of Shelter::adopt() rely on getting a Dog:
<?php
class Animal {}
class Dog extends Animal {}
class Shelter
{
public function adopt(string $name): Dog
{
return new Dog();
}
}
class BadShelter extends Shelter
{
public function adopt(string $name): Animal
{
return new Animal();
}
}
Output:
Fatal error: Declaration of BadShelter::adopt(string $name): Animal must be compatible with Shelter::adopt(string $name): Dog in ... on line 15
Adding a required parameter breaks every existing call $repo->find($id):
<?php
class Repo
{
public function find(int $id): ?array
{
return null;
}
}
class CachedRepo extends Repo
{
public function find(int $id, bool $useCache): ?array
{
return null;
}
}
Output:
Fatal error: Declaration of CachedRepo::find(int $id, bool $useCache): ?array must be compatible with Repo::find(int $id): ?array in ... on line 12
The fix is bool $useCache = true.
Narrowing a parameter type is also an error. The parent promised to accept int|string, so a child accepting only int would break callers passing strings:
<?php
class Repo
{
public function find(int|string $id): ?array
{
return null;
}
}
class IntRepo extends Repo
{
public function find(int $id): ?array
{
return null;
}
}
Output:
Fatal error: Declaration of IntRepo::find(int $id): ?array must be compatible with Repo::find(string|int $id): ?array in ... on line 12
An untyped parameter is treated as mixed, the widest type, so a child can't add a narrower type to it. A child can, however, add a return type to a method that had none. This is useful when modernizing a subclass of legacy code:
<?php
class Legacy
{
public function save($data)
{
}
}
class Modern extends Legacy
{
// untyped param is effectively mixed: any type is wider or equal
public function save(mixed $data): void
{
echo "saved ", json_encode($data), "\n";
}
}
(new Modern())->save(['a' => 1]);
Output:
saved {"a":1}
Switching between static and instance methods is always an error:
<?php
class Base
{
public function make(): static
{
return new static();
}
}
class Child extends Base
{
public static function make(): static
{
return new static();
}
}
Output:
Fatal error: Cannot make non static method Base::make() static in class Child in ... on line 12
Parameter names don't have to match, but since PHP 8.0 callers can use named arguments, so renaming a parameter in an override can break $obj->find(id: 5). Keep the names the same.
Visibility
An override may make a method more visible (protected to public), but not less visible. Code that could call the parent method must be able to call the override:
<?php
class Base
{
protected function hook(): string
{
return 'base';
}
}
class Child extends Base
{
// protected -> public: allowed
public function hook(): string
{
return 'child';
}
}
class Broken extends Base
{
// protected -> private: not allowed
private function hook(): string
{
return 'broken';
}
}
Output:
Fatal error: Access level to Broken::hook() must be protected (as in class Base) or weaker in ... on line 22
Private methods are not overridden
A private method is invisible to child classes. A child method with the same name is a new, unrelated method, and none of the signature rules apply. Calls inside the parent class still go to the parent's private method:
<?php
class Base
{
public function run(): string
{
return $this->step();
}
private function step(): string
{
return 'Base::step';
}
}
class Child extends Base
{
// not an override: Base::step is private, so this is an unrelated method
// with the same name, free to have any signature
public function step(int $times = 1): string
{
return 'Child::step';
}
}
$c = new Child();
echo $c->run(), "\n";
echo $c->step(), "\n";
Output:
Base::step
Child::step
If you want subclasses to customize a step, make it protected. See Method and Property Visibility.
The #[\Override] attribute
A classic bug: you override a method, and later someone renames or removes the parent method. Your method silently stops being an override and is never called. Similarly, a typo in the method name (sendMial) creates a new method instead of overriding.
PHP 8.3 added the #[\Override] attribute. It tells the engine that the method must override a parent method or implement an interface method. If no such method exists, the class fails to compile:
<?php
class Mailer
{
public function send(string $to, string $body): bool
{
return true;
}
}
class QueuedMailer extends Mailer
{
#[\Override]
public function send(string $to, string $body): bool
{
echo "queued mail to $to\n";
return true;
}
#[\Override]
public function sendLater(string $to, string $body): bool
{
return true;
}
}
Output:
Fatal error: QueuedMailer::sendLater() has #[\Override] attribute, but no matching parent method exists in ... on line 20
send() passes the check; sendLater() doesn't override anything. Use the leading backslash (#[\Override]) or use Override; inside namespaced code, otherwise PHP looks for an attribute class in the current namespace and the check is silently skipped. Static analyzers such as PHPStan can be configured to require #[\Override] on every override. More attributes are covered in Attributes.
Preventing overriding with final
Mark a method final to forbid overriding it. A common use is the template method pattern: the parent defines the algorithm in a final method and lets children override only specific steps:
<?php
class Report
{
final public function render(): string
{
return $this->header() . "\n" . $this->body();
}
protected function header(): string
{
return '== Report ==';
}
protected function body(): string
{
return '(empty)';
}
}
class SalesReport extends Report
{
protected function body(): string
{
return 'Total: 1234';
}
}
echo (new SalesReport())->render(), "\n";
Output:
== Report ==
Total: 1234
Trying to override render() in a subclass:
class Hacked extends Report
{
public function render(): string
{
return 'hacked';
}
}
Output:
Fatal error: Cannot override final method Report::render() in ... on line 32
A final class can't be extended at all. See Final Keyword.
Overriding abstract and interface methods
Implementing an abstract method or an interface method follows the same signature rules. A concrete class can override a method that was already implemented by its parent, and #[\Override] works for both cases:
<?php
interface Exporter
{
public function export(array $rows): string;
}
abstract class BaseExporter implements Exporter
{
abstract protected function line(array $row): string;
public function export(array $rows): string
{
return implode("\n", array_map($this->line(...), $rows));
}
}
class CsvExporter extends BaseExporter
{
#[\Override]
protected function line(array $row): string
{
return implode(',', $row);
}
}
class TsvExporter extends CsvExporter
{
#[\Override]
protected function line(array $row): string
{
return implode("\t", $row);
}
}
$rows = [['id', 'name'], [1, 'Ada'], [2, 'Linus']];
echo (new CsvExporter())->export($rows), "\n---\n";
echo (new TsvExporter())->export($rows), "\n";
Output:
id,name
1,Ada
2,Linus
---
id name
1 Ada
2 Linus
Overriding constructors
Constructors are special: an overriding constructor may have a completely different signature, because constructors are called on a concrete class (new Child(...)), not through a parent-typed reference. The exception is a constructor declared abstract or in an interface, which then must be matched.
If a child defines its own constructor, the parent constructor is not called automatically. You must call parent::__construct() yourself:
<?php
class Base
{
public function __construct()
{
echo "Base::__construct\n";
}
}
class NoCtor extends Base {}
class Forgets extends Base
{
public function __construct()
{
echo "Forgets::__construct\n";
}
}
class Calls extends Base
{
public function __construct(public string $name)
{
parent::__construct();
echo "Calls::__construct($name)\n";
}
}
new NoCtor();
echo "--\n";
new Forgets();
echo "--\n";
new Calls('x');
Output:
Base::__construct
--
Forgets::__construct
--
Base::__construct
Calls::__construct(x)
NoCtor inherits the parent constructor. Forgets replaces it, so the parent's initialization never happens. More on this in Calling a parent constructor when instantiating a child.
Pitfall: calling overridable methods from a constructor
If a parent constructor calls a method that the child overrides, the child's version runs before the child constructor has finished:
<?php
class Base
{
public function __construct()
{
echo "Base sees: ", $this->label(), "\n";
}
protected function label(): string
{
return 'base';
}
}
class Child extends Base
{
private string $prefix;
public function __construct()
{
parent::__construct(); // runs Child::label() before $prefix is set
$this->prefix = 'child';
}
protected function label(): string
{
return $this->prefix . ' label';
}
}
new Child();
Output:
Base sees:
Fatal error: Uncaught Error: Typed property Child::$prefix must not be accessed before initialization in ...:27
Either initialize the child's state before calling parent::__construct(), or avoid calling overridable methods from constructors:
public function __construct()
{
$this->prefix = 'child'; // initialize own state first
parent::__construct();
}
Output:
Base sees: child label
Overriding static methods
Static methods can be overridden too, but whether the override is used depends on how the parent calls it. self:: always refers to the class where the code is written; static:: refers to the class the method was called on (late static binding):
<?php
class Model
{
public static function table(): string
{
return 'models';
}
public static function selfQuery(): string
{
return 'SELECT * FROM ' . self::table();
}
public static function staticQuery(): string
{
return 'SELECT * FROM ' . static::table();
}
}
class User extends Model
{
public static function table(): string
{
return 'users';
}
}
echo User::table(), "\n";
echo User::selfQuery(), "\n";
echo User::staticQuery(), "\n";
Output:
users
SELECT * FROM models
SELECT * FROM users
If a static method is meant to be overridden, call it with static::. Details in Late static binding.
Overriding constants
Class constants can be redefined in a child class. The same self:: versus static:: distinction applies:
<?php
class Http
{
const TIMEOUT = 30;
final public const VERSION = '1.1';
public function timeout(): int
{
return static::TIMEOUT;
}
public function selfTimeout(): int
{
return self::TIMEOUT;
}
}
class SlowHttp extends Http
{
const TIMEOUT = 120;
}
$h = new SlowHttp();
echo SlowHttp::TIMEOUT, "\n";
echo $h->timeout(), "\n";
echo $h->selfTimeout(), "\n";
echo SlowHttp::VERSION, "\n";
Output:
120
120
30
1.1
Since PHP 8.1 a constant can be final, which forbids redefining it:
<?php
class Http
{
final public const VERSION = '1.1';
}
class Http2 extends Http
{
public const VERSION = '2';
}
Output:
Fatal error: Http2::VERSION cannot override final constant Http::VERSION in ... on line 7
Constants declared in an interface could not be overridden before PHP 8.1; since 8.1 they can, unless they are final.
Overriding properties
A child can redeclare an inherited property, typically to change its default value. Visibility may be widened, as with methods:
<?php
class Widget
{
protected string $color = 'gray';
protected int $size = 10;
public function describe(): string
{
return "{$this->color} widget, size {$this->size}";
}
}
class RedWidget extends Widget
{
// redeclare to change the default value
protected string $color = 'red';
// visibility may be widened, like methods
public int $size = 20;
}
echo (new Widget())->describe(), "\n";
$w = new RedWidget();
echo $w->describe(), "\n";
$w->size = 25;
echo $w->describe(), "\n";
Output:
gray widget, size 10
red widget, size 20
red widget, size 25
There is only one property per object: the parent's methods see the child's default. Unlike methods, property types are invariant, because properties are both read and written:
<?php
class Widget
{
protected int $size = 10;
}
class FloatWidget extends Widget
{
protected float $size = 10.5;
}
Output:
Fatal error: Type of FloatWidget::$size must be int (as in class Widget) in ... on line 7
If you only need a different default, it's often cleaner to set it in the child's constructor instead of redeclaring the property.
Adding property hooks (PHP 8.4)
PHP 8.4 property hooks can be added to an inherited property in a child class. This lets a subclass validate or normalize values without changing the parent:
<?php
class Person
{
public string $name = '';
}
class Customer extends Person
{
// PHP 8.4: add a set hook to an inherited property
public string $name = '' {
set => ucwords(trim($value));
}
}
$p = new Person();
$p->name = ' ada lovelace ';
var_dump($p->name);
$c = new Customer();
$c->name = ' ada lovelace ';
var_dump($c->name);
Output:
string(15) " ada lovelace "
string(12) "Ada Lovelace"
Traits and precedence
When a class uses a trait, the precedence order is:
- methods declared in the class itself
- methods from the trait
- methods inherited from the parent class
So a trait method overrides an inherited method, and a class method overrides a trait method. Inside a trait method, parent:: refers to the parent of the class that uses the trait:
<?php
class Base
{
public function hello(): string
{
return 'Base::hello';
}
}
trait Greets
{
public function hello(): string
{
return 'Greets::hello, then ' . parent::hello();
}
}
class UsesTrait extends Base
{
use Greets;
}
class OwnMethod extends Base
{
use Greets;
public function hello(): string
{
return 'OwnMethod::hello';
}
}
echo (new UsesTrait())->hello(), "\n";
echo (new OwnMethod())->hello(), "\n";
Output:
Greets::hello, then Base::hello
OwnMethod::hello
Summary
- Declaring a method with the same name in a child class overrides it; calls through
$thisin the parent dispatch to the override. - Use
parent::method()to extend rather than replace the parent's behavior. Parent constructors are not called automatically. - Overrides may narrow return types, widen parameter types, add optional parameters and widen visibility. Anything else is a fatal error at class declaration. Keep parameter names the same for named arguments.
privatemethods are not overridden; a same-named child method is unrelated.- Put
#[\Override]on every override (PHP 8.3+) so renaming a parent method can't silently break it. - Use
finalon methods, constants and classes that must not be changed by subclasses. - Call overridable static methods and constants via
static::, notself::. - Property types are invariant; you can change defaults, widen visibility and (PHP 8.4) add hooks.
- Avoid calling overridable methods from constructors, or initialize child state before
parent::__construct().