« NoDiscard::__construct
Override::__construct »

Override アトリビュート

(PHP 8 >= 8.3.0)

はじめに

このアトリビュートは、 親クラスのメソッドやプロパティをオーバーライドしている意図があるか、 インターフェイスで定義されたプロパティやメソッドを実装していることを示します。

親クラス中に同じ名前のメソッドやプロパティが存在しなかったり、 実装されているインターフェイスがない場合は、 コンパイル時にエラーが発生します。

シグネチャのチェックを回避できてしまうため、 このアトリビュートは __construct() に対しては使えません。

クラス概要

#[\Attribute(
    \Attribute::TARGET_METHOD
    | \Attribute::TARGET_PROPERTY,
)]

final class Override {
/* メソッド */
public function __construct()
}

変更履歴

バージョン 説明
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

目次

関連キーワード:
Override   アトリビュート   construct   プロパティ   Base   protected   Extended   Attribute   final   インターフェイス   実装   一緒   extends   attribute   matching   parent   exists   NoDiscard   オーバーライド   意図   コンパイル   シグネチャ   チェック   回避   概要
関連する関数・ページ:
override.construct   reserved.attributes   class.delayedtargetvalidation   class.attribute   language.attributes   language.attributes.classes