Closed
Description
Description
When adding the #[Override]
attribute to a trait method, then use-ing it in a class, a runtime error is triggered even if a parent class defines a matching method. This does not happen when an interface with matching signature is encountered.
The following excerpt from the rfc made me expect this would work:
Methods from a used trait behave as if the method definition was copied and pasted into the target class. Specifically the #[\Override] attribute on a trait method requires the existence of a matching method in a parent class or implemented interface.
The following code:
<?php
class A {
public function foo(): void {}
}
interface I {
public function foo(): void;
}
trait T {
#[\Override]
public function foo(): void {
echo 'foo';
}
}
// Works fine
class B implements I {
use T;
}
// Works fine ("copied and pasted into the target class")
class C extends A {
#[\Override]
public function foo(): void {
echo 'foo';
}
}
// Does not work
class D extends A {
use T;
}
Resulted in this output:
PHP Fatal error: D::foo() has #[\Override] attribute, but no matching parent method exists in mwe.php on line 13
PHP Stack trace:
PHP 1. {main}() mwe.php:0
Fatal error: D::foo() has #[\Override] attribute, but no matching parent method exists in mwe.php on line 13
Call Stack:
0.0002 364504 1. {main}() mwe.php:0
But I expected no output instead.
PHP Version
8.3.0RC1
Operating System
Windows 11 / Ubuntu 23.10 with WSL