On Tuesday, 27 August 2024 at 09:25, Brent Roose <[email protected]>
wrote:
> Back to PHP, using traits as types seems impossible, since traits are a
> compile-time copy/paste mechanism, which means there’s no type information
> available about them at runtime.
>
> However, allowing traits to implement interfaces would solve this problem:
> these interfaces would be copied over to classes during compile-time, and the
> interface’s type information is available at runtime. On top of that, traits
> already have well-defined rules for conflict resolution, so we wouldn’t need
> any additional syntax to handle edge cases.
Traits are very ill-suited for this because everything from a trait can be
overwritten:
trait T {
public function foo(string $v): int {}
}
class C {
use T;
public function foo(array $v): string {}}
This is valid code, now imagine T implements interface I:
interface I {
public foo(string $v): int;
}
C cannot implement I, moreover the conflict resolution mechanism just exposes
more problems as you can rename a method from a trait, or change its visibility.
> -
>
> Even though it was not accepted, the interface default methods RFC approached
> the problem from a different angle [4].
>
> -
>
> While a majority disagreed that interfaces should implement their own methods
> directly, I remember it was a heavily debated topic, and believe that
> approaching it from the other side might be easier to accept.
One part of the contention came that this feature was proposed in June of 2023,
weeks before feature freeze, and that no attempt at restricting the
implementation of the default implementation was made.
I still think default methods for interfaces make more sense then trying to fix
traits, but also default implementations only really make sense for interfaces
with multiple methods where one is a "core" method that remains abstract and
the default implementations rely on it to be implemented.
As such I am not really convinced of the utility of adding interface support
for traits considering all the issues I can foresee happenning.
Best regards,
Gina P. Banyard
>