> 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 don't think there's any insurmountable obstacles, but it would be useful to add a lot of tests because of potential edge cases (resolution, opcache, reference counting) involved in traits and adding new places where constants can go. (I'd also worked on a declined RFC and implementation for changing what could be used in a constant expression) ``` <?php trait T { // Similarly, if constants could be declared in traits, // it would be useful to have the same behavior of `echo ClassOrTrait::MY_CONST`. // const MY_CONST = self::OTHER_CONST // const MY_CONST_2 = self::CONST_DEFINED_BOTH_IN_TRAIT_AND_CLASS // // MY_CONST_2 could probably be correctly implemented if // subclasses copied the AST of the class constant's expression // instead of the evaluated value if self:: or static:: (or __CLASS__?) were referenced. public static function main($x = self::OTHER_CONST) { echo $x, "\n"; } } // Getting reference counting correct is important to test // strtolower() is locale-dependent, so the value isn't immutable. define('REFERENCE_COUNTED_VALUE', strtolower('From C')); class C { use T; const OTHER_CONST = REFERENCE_COUNTED_VALUE; } class D { use T; const OTHER_CONST = 'From D'; } C::main(); try { T::main(); } catch (Throwable $x) { echo $x->getMessage() . "\n"; } D::main(); /* Output: from c Undefined class constant 'self::OTHER_CONST' >From D */ ``` - Tyson -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php