On Sun, Apr 18, 2021 at 4:20 PM Máté Kocsis <kocsismat...@gmail.com> wrote:

> Hi Internals,
>
> I've recently realized that class constant values cannot always be trusted
> when late static binding is involved (e.g. static::FOO or $this::FOO),
> since they can be freely overridden in child classes. That's why the engine
> knows neither the type and the value before run-time.
>
> Doctrine coding standards has a specific rule which disallows referencing a
> possibly overridden class constant (
>
> https://github.com/doctrine/coding-standard/blob/8d75920bb04a9be4c73c2a775ee5766262cf2a0d/lib/Doctrine/ruleset.xml#L123
> ),
> but I'm wondering if it would be better to simply make it possible to allow
> declaring class constants final  (thus disallowing overriding) instead?
>
> In my opinion, final constants would come with two advantages:
> - make class constant declarations paranoidly safe
> - allow the engine to optimize class constants references in LSB context
>
> Although I admit that the win is not extra huge, I do think that it would
> still be useful to have this feature, especially considering that the
> implementation is very straightforward (
> https://github.com/php/php-src/pull/6878). So that's why I'm proposing
> this
> as an RFC.
>
> Recently, a similar attempt to make class constant declarations safer was
> the Typed Constants RFC (https://externals.io/message/110755#110755), but
> unfortunately it has halted since then. I think final and typed constants
> would be a nice little addition, and would complement each other well.
>
> Regards,
> Máté
>

I think if we add final class constants, we should also clean up the
current semantics for class constant overriding at the same time. The
problem is that interface constants currently cannot be overridden directly
(https://3v4l.org/jsDRO), but they can be overridden indirectly (
https://3v4l.org/IkvJe). If we have final class constants, then we should
say that class constants are always overridable by default (regardless of
whether they are declared in an interface or class), as we now have an
explicit way to opt into forbidding the override.

Regards,
Nikita

Reply via email to