phpday 2027 - Call for Papers

The Override attribute

(PHP 8 >= 8.3.0)

Giriş

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.

Sınıf Sözdizimi

/* Yöntemler */
public function __construct()
}

Sürüm Bilgisi

Sürüm: Açıklama
8.6.0 Override can be applied to class constants, including enum cases.
8.5.0 Override can be applied to properties.

Örnekler

Örnek 1 Usage with methods

<?php

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

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

?>

Yukarıdaki örneğin PHP 8.3 çıktısı şuna benzer:

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

Örnek 2 Usage with properties

<?php

class Base {
    protected string $foo;
}

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

?>

Output of the above example in PHP 8.5 is similar to:

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

Örnek 3 Usage with class constants

<?php

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

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

?>

Output of the above example in PHP 8.6 is similar to:

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

Ayrıca Bakınız

İçindekiler

User Contributed Notes

There are no user contributed notes for this page.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top