Re: [PHP-DEV] Trait constants

This is only part of a thread. view whole thread
  110750
June 27, 2020 19:09 tysonandre775@hotmail.com (tyson andre)
> It’s always struck me as slightly odd that traits don’t support constants the way classes and interfaces do. > I tried to find an explanation of the lack of support in the original RFC, and came up empty. > > A consequent discussion in R11 has led me here. > Can anyone working on internals explain why traits don’t allow constants (either technically or philosophically)? > Moreover, what’s the opinion(s) of the list, on adding support for this? Would an RFC be needed?
I'm in favor of adding it. I doubt there's any insurmountable technical obstacles. (I work on a static analyzer for php (https://github.com/phan/phan) and don't expect technical issues with that proposal) I personally find it inconvenient to put constants used by traits in different classes/interfaces or in properties. Other languages allow adding constants to traits: - Java allows defining constants on interfaces, which allow defining default method implementations like PHP traits - https://doc.rust-lang.org/edition-guide/rust-2018/trait-system/associated-constants.html allows defining constants with values on traits (it also does various other things that impractical for php) One thing to document/add tests for would be the resolution of `self::MY_CONST`. In a trait, `self::method()` may be overridden by the method of the class that's using the trait. I'd expect `self::MY_CONST` to be the same. ```php https://www.php.net/manual/en/language.oop5.traits.php#language.oop5.traits.conflict (e.g. `use A, B { const A::MY_CONST insteadof B; }`) - We already check if there are conflicting values when inheriting constants from an interface and another interface/trait. Cheers, - Tyson