php8.5
Home/ Manual/ predefined / attributes/ The Override attribute

The Override attribute

This attribute is used to indicate that a method, a property, or a class constant (including an enum case) is intended to override a method, a property, or a class constant of a parent class or that it implements a method, a property, or a class constant defined in an interface.

Intro

This attribute is used to indicate that a method, a property, or a class constant (including an enum case) is intended to override a method, a property, or a class constant of a parent class or that it implements a method, a property, or a class constant defined in an interface.

If no method, property, or class constant with the same name exists in a parent class or in an implemented interface a compile-time error will be emitted.

The attribute cannot be used on the __construct() method, which is exempt from signature checks.

Class synopsis

#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY | \Attribute::TARGET_CLASS_CONSTANT)] Override { }

Changelog

VersionDescription
8.6.0Override can be applied to class constants, including enum cases.
8.5.0Override can be applied to properties.

Examples

Usage with methods

php
<?php

class Base {
    protected function foo(): void {}
}

final class Extended extends Base {
    #[\Override]
    protected function boo(): void {}
}

?>

Similar

output
Fatal error: Extended::boo() has #[\Override] attribute, but no matching parent method exists

Usage with properties

php
<?php

class Base {
    protected string $foo;
}

final class Extended extends Base {
    #[\Override]
    protected string $boo;
}

?>

Similar

output
Fatal error: Extended::$boo has #[\Override] attribute, but no matching parent property exists

Usage with class constants

php
<?php

class Base {
    protected const FOO = 'foo';
}

final class Extended extends Base {
    #[\Override]
    protected const BOO = 'boo';
}

?>

Similar

output
Fatal error: Extended::BOO has #[\Override] attribute, but no matching parent constant exists

See Also

Construct

In this section

Source: language/predefined/attributes/override.xml · from the official PHP manual (php/doc-en)