Re: Typed constants revisited
| From: | Larry Garfield | Date: | Thu, 24 Mar 2022 17:47:25 +0000 |
| Subject: | Re: Typed constants revisited | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-117418@lists.php.net to get a copy of this message | ||
On Thu, Mar 24, 2022, at 11:34 AM, Mark Niebergall wrote:
> Pierre,
>
> On Thu, Mar 24, 2022 at 9:20 AM Pierre <pierre-php@processus.org> wrote:
>
>> Le 24/03/2022 à 16:06, Mark Niebergall a écrit :
>> > 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.
>>
>> That was exactly my point: the type could simply implicitely be the one
>> of the original value.
>>
>> Then the engine just has to use the existing covariance/contravariance
>> rules for type checks based upon the guessed value type. This would fix
>> the type safety issue you are referring to.
>>
>
> I'd rather not use the "guessed value type" in code, that tends to lead to
> bugs: guessing = bugs. Explicitly declaring the type avoids the pitfalls of
> guessing and ensures code predictability. It also comes with added
> benefits, including self-documenting code, defined inheritance requirements
> (the way you describe would have BC breakage), and (for some IDEs) type
> hinting.
>
> Of note, many other languages already have typed constants. Yes this is the
> "everyone else is doing it" argument, but they had their valid reasons.
> Some are strong typed languages, others are not. See:
>
> - Go: https://go.dev/blog/constants
> - HVVM: https://docs.hhvm.com/hack/classes/type-constants
> - C: https://fresh2refresh.com/c-programming/c-constants/
> - C++: https://en.cppreference.com/w/c/language/const
> - C#:
>
> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const
The addition of union types put the kibosh on successfully type guessing, I think. If you have a
const that you'll allow a float or int in, and the default is 0, the guesser will guess int,
not float, and then you can't allow a float.
So "constant inheritance" is a use case for typed constants, even if constant inheritance
is a rather edge-case situation to begin with.
--Larry Garfield