Re: [PHP-DEV] Typed constants

This is only part of a thread. view whole thread
  110757
June 28, 2020 12:35 nikita.ppv@gmail.com (Nikita Popov)
On Sun, Jun 28, 2020 at 2:03 PM Benas IML iml@gmail.com> wrote:

> Hey internals, > > Is there any particular reason as to why constants cannot be typed? For > example: > > ``` > class Test { > // this is illegal > public const int TEST = 1; > } > ``` > > Having typed constants would be quite beneficial. First of all, we > would obviously be more consistent with properties and functions ;) > But also, we could ensure that the correct type is retained during > inheritance. For example: > > ``` > class Test { > public const TEST = 0; > } > > class Test2 extends Test { > // this is legal (even though the type is different) > public const TEST = 'abc'; > } > ``` > > ...but with typed constants, this would be possible: > > ``` > class Test { > // this is legal > public const int TEST = 0; > } > > class Test2 extends Test { > // this is illegal since the type is not declared > public const TEST = 'abc'; > } > > class Test3 extends Test { > // this is illegal since the type is not an integer > public const string TEST = 'abc'; > } > > class Test4 extends Test { > // this is illegal since the value is not an integer > public const int TEST = 'abc'; > } > > class Test5 extends Test { > // this is legal > public const int TEST = 1; > } > ``` > > Moreover, even the PHP manual (e. g. > https://www.php.net/manual/en/class.reflectionclass.php) and numerous > RFCs (e. g. https://wiki.php.net/rfc/attribute_amendments) specify the > type for constants. This may confuse newcomers since that is actually > not allowed in PHP. > > I am prepared to do all of the hard work and implement this myself, if > other internals also find this proposal a good idea. > > Best regards, > Benas Seliuginas >
Typing constants isn't terribly useful, because the type of the constant is already determined by its immutable value, which is not the case for property types or function return types. However, I do support allowing types for class constants in the interest of overall language consistency. Nikita
  110760
June 28, 2020 15:40 sebastian@php.net (Sebastian Bergmann)
Am 28.06.2020 um 14:35 schrieb Nikita Popov:
I do support allowing types for class constants in the interest of overall 
language consistency.

Same here: +1