CakeFest 2025 Madrid: The Official CakePHP Conference

The Override attribute

(PHP 8 >= 8.3.0)

Introduction

This attribute is used to indicate that a method is intended to override a method of a parent class or that it implements a method defined in an interface.

If no method with the same name exists in a parent class or in an implemented interface a compile-time error will be emitted.

Class synopsis

final class Override {
/* Methods */
public __construct()
}

Examples

<?php

class Base {
protected function
foo(): void {}
}

final class
Extended extends Base {
#[
\Override]
protected function
boo(): void {}
}

?>

Output of the above example in PHP 8.3 is similar to:

Fatal error: Extended::boo() has #[\Override] attribute, but no matching parent method exists

Table of Contents

add a note

User Contributed Notes 1 note

up
0
alxrie at gmail dot com
5 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