Pierre,

On Thu, Mar 24, 2022 at 1:04 AM Pierre <pierre-...@processus.org> wrote:

> Le 23/03/2022 à 23:10, Larry Garfield a écrit :
> > Is there a benefit to it other than "well everything else has types now,
> so..."?  Even if it's esoteric, like in reflection-based meta programming?
> (I've been dabbling too much in that lately. :-) )  "Everything else does"
> isn't a compelling argument for me, but there may be others I'm not
> thinking of.
> >
> > --Larry Garfield
> >
> Hello,
>
> Well I was thinking myself that const being well... constant, and so
> always defined, type could be determined at compile time without the
> need to express it in a verbose way.
>
> PHP doesn't do any static type inference, but in this case, it could be
> done almost for free, am I wrong ? If it was determined at compile time,
> then the type checking on overrides would only be trivial, using the
> parent occurrence value inferred type. My point is that there's no need
> to express the type of a value, the value has already has a type.
>

As a developer, I don't *always* trust other developers implementing my
code. Referring back to the Bird and EmperorPenguin example, the expected
type for `public const bool CAN_FLY;` example MUST be a bool. If it isn't
typed, another developer _could_ incorrectly set `CAN_FLY = 1;` or `CAN_FLY
= 'true';` or even `CAN_FLY = 'Y';`. With class constants typed, they would
get an error if setting it to anything other than a bool `CAN_FLY = true;`
or `CAN_FLY = false;`. This further proliferates into sending the value of
`CAN_FLY` into a typed argument like `protected function
determineModeOfTransport(bool $canFly)` - if the constant is set
incorrectly as a string or integer then more errors can occur.

Typing class constants could also help static code analyzers more easily
determine if there are bugs with unexpected value types being used in code.
Instead of determining the value of the constant, the type of the constant
could be used instead, providing a cleaner tokenized parsing.

So you are correct, the const value does have a value that has a type, but
there is no way to enforce which type the value is or to use const with
inheritance, which is part of the bigger picture here.



>
> Regards,
>
> --
>
> Pierre
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Reply via email to