大网数据广告活动
PHP 语言与运行手册

Override 注解

· 52CE 我爱测

此注解用于表明某个方法、属性或类常量(包括枚举 case)意图重写父类中的方法、属性或类常量,或实现接口中定义的方法、属性或类常量。

Override 注解

(PHP 8 >= 8.3.0)

简介

此注解用于表明某个方法、属性或类常量(包括枚举 case)意图重写父类中的方法、属性或类常量,或实现接口中定义的方法、属性或类常量。

如果父类或实现的接口中不存在同名的方法、属性或类常量,则会引发编译时错误。

此注解不能用于 __construct() 方法,该方法不进行签名检查。

类摘要

/* 方法 */
public function __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

参见

目录

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。