CakeFest 2025 Madrid: The Official CakePHP Conference

Override 属性

(PHP 8 >= 8.3.0)

简介

此属性用于表明方法意图重写父类中的方法或实现接口中定义的方法。

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

类摘要

final class Override {
/* 方法 */
public __construct()
}

示例

<?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

参见

目录

添加备注

用户贡献的备注 1 note

up
0
alxrie at gmail dot com
4 days ago
The magic method __construct() can't be marked with Override attribute.

For example:

class Base {
public $val;
public function __construct() {
$this->val = 0;
}
}

class Derived extends Base {
#[\Override]
public function __construct() {
parent::__construct();
++$this->val;
}
}

In PHP 8.3 this example raises an error message

Fatal error: Derived::__construct() has #[\Override] attribute, but no matching parent method exists
To Top