Override 注解
(PHP 8 >= 8.3.0)
简介
此注解用于表明某个方法、属性或类常量(包括枚举 case)意图重写父类中的方法、属性或类常量,或实现接口中定义的方法、属性或类常量。
如果父类或实现的接口中不存在同名的方法、属性或类常量,则会引发编译时错误。
此注解不能用于 __construct() 方法,该方法不进行签名检查。
类摘要
#[\Attribute(
\Attribute::TARGET_METHOD
| \Attribute::TARGET_PROPERTY
| \Attribute::TARGET_CLASS_CONSTANT,
)]
final class Override {
\Attribute::TARGET_METHOD
| \Attribute::TARGET_PROPERTY
| \Attribute::TARGET_CLASS_CONSTANT,
)]
final class Override {
/* 方法 */
}更新日志
| 版本 | 说明 |
|---|---|
| 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
参见
目录
- Override::__construct — 构造新的 Override 属性实例
来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。
