CakeFest 2025 Madrid: The Official CakePHP Conference

Das Attribut Override

(PHP 8 >= 8.3.0)

Einführung

Dieses Attribut wird verwendet, um anzuzeigen, dass eine Methode eine Methode einer Elternklasse überschreiben soll oder dass sie eine in einer Schnittstelle definierte Methode implementiert.

Wenn es weder in einer Elternklasse noch in einer implementierten Schnittstelle eine Methode mit demselben Namen gibt, wird ein Kompilierungsfehler ausgegeben. emitted.

Klassenbeschreibung

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

Beispiele

<?php

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

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

?>

Das oben gezeigte Beispiel erzeugt mit PHP 8.3 eine ähnliche Ausgabe wie:

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

Inhaltsverzeichnis

add a note

User Contributed Notes 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