(PHP 8 >= 8.3.0)
このアトリビュートは、 メソッド、プロパティ、クラス定数(列挙型の case を含む)が、 親クラスのものをオーバーライドする意図で宣言されていること、 またはインターフェイスで定義されたものを実装していることを示します。
親クラスにも、実装しているインターフェイスにも、 同じ名前のメソッド、プロパティ、クラス定数が存在しない場合、 コンパイル時にエラーが発生します。
シグネチャのチェックを回避できてしまうため、 このアトリビュートは __construct() に対しては使えません。
| バージョン | 説明 |
|---|---|
| 8.6.0 | Override は、 列挙型の case を含むクラス定数にも適用できるようになりました。 |
| 8.5.0 | Override は、 プロパティにも適用できるようになりました。 |
例1 メソッドと一緒に使う
<?php
class Base {
protected function foo(): void {}
}
final class Extended extends Base {
#[\Override]
protected function boo(): void {}
}
?>上の例の PHP 8.3 での出力は、たとえば以下のようになります。:
Fatal error: Extended::boo() has #[\Override] attribute, but no matching parent method exists
例2 プロパティと一緒に使う
<?php
class Base {
protected string $foo;
}
final class Extended extends Base {
#[\Override]
protected string $boo;
}
?>上の例の PHP 8.5 での出力は、たとえば以下のようになります。:
Fatal error: Extended::$boo has #[\Override] attribute, but no matching parent property exists
例3 クラス定数と一緒に使う
<?php
class Base {
protected const FOO = 'foo';
}
final class Extended extends Base {
#[\Override]
protected const BOO = 'boo';
}
?>上の例の PHP 8.6 での出力は、たとえば以下のようになります。
Fatal error: Extended::BOO has #[\Override] attribute, but no matching parent constant exists