2017-06-28 13:59 GMT-03:00 Kalle Sommer Nielsen <[email protected]>:
> Hi David
>
> 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]
>
Not on reality. :(
The "final" keyworks make a "local scope" variable value "blocked to
rewrite" after instantiate it.
Okay, it sounds like a "const", and it is, but "not as we known it".
While constants are class member (or globals), a final variable is just a
variable blocked to rewrite, and it could be initialized with a new data
content every time that the context is called (eg. a function).
For instance (note that the parameter is "final", then I can't modify the
parameter variable, but it can receives a new value each time that I call
this function):
function write(final $message) { echo $message; }
write("Hello");
write("World");
// Write "Hello World" on ouput.
Or then:
function randomNumber() {
final $number = mt_rand();
echo $number;
// $number = mt_rand_again(); // <-- will not be allowed!
}
randomNumber();
// Write "0.123"
randomNumber();
// Write "0.456"
>
> [1] http://php.net/constants
> [2] https://docs.microsoft.com/en-us/dotnet/csharp/language-
> reference/keywords/readonly
>
--
David Rodrigues