Re: Final variables
| From: | Kalle Sommer Nielsen | Date: | Wed, 28 Jun 2017 16:59:51 +0000 |
| Subject: | Re: Final variables | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-99658@lists.php.net to get a copy of this message | ||
Hi David
2017-06-28 18:10 GMT+02:00 David Rodrigues <david.proweb@gmail.com>:
> Hello internals,
>
> Java supports the "final" keyword before a variable to determines that this
> variables never change it reference. If I declare a variable as "final", I
> can only initialize that once, then I could not change it after (but I can
> manipulate the instance, without issues).
>
> There some special reason to PHP doesn't supports things like that?
It seems like what you are looking for here is actually a constant[1].
However constants do not support non scalar types, such as array or
objects, what would really solve it on the objects side of things
would be the introduction of a "readonly" keyword or similar, like
that of C#[2]
> final $number = 123;
> $number = 456; // Error: you change change final variables.
>
> final $object = new stdClass;
> $object->allowed = true; // No error.
>
> This feature make sense because it tells to dev that the variable value
> could not be updated directly (new reference). Which make easy to identify
> when a variable is modifiable or not.
>
> It is valid for a RFC?
>
> - It can uses the "final" keyword;
> - It doesn't a BC;
Anything is usually valid for an RFC, however I think (personally)
that this should rather be an RFC for a readonly keyword if anything
> I too think that a final variable can be useful to make some internal
> improvements on language (but it could be a BC for PHP internals). I mean,
> as the variable could not be modified, then it don't need be a "flexible"
> type internally (I guess that it is a zval, right?).
>
> Reference:
> https://github.com/kalessil/phpinspectionsea/issues/363
>
> --
> David Rodrigues
[1] http://php.net/constants
[2] https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly
--
regards,
Kalle Sommer Nielsen
kalle@php.net