Override アトリビュート

はじめに

このアトリビュートは、 メソッド、プロパティ、クラス定数(列挙型の case を含む)が、 親クラスのものをオーバーライドする意図で宣言されていること、 またはインターフェイスで定義されたものを実装していることを示します。

親クラスにも、実装しているインターフェイスにも、 同じ名前のメソッド、プロパティ、クラス定数が存在しない場合、 コンパイル時にエラーが発生します。

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

クラス概要

#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY | \Attribute::TARGET_CLASS_CONSTANT)] final Override
/* メソッド */
public __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
目次