Re: Final variables
| From: | Kalle Sommer Nielsen | Date: | Thu, 29 Jun 2017 02:57:12 +0000 |
| Subject: | Re: Final variables | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-99669@lists.php.net to get a copy of this message | ||
2017-06-29 1:07 GMT+02:00 David Rodrigues <david.proweb@gmail.com>:
> readonly $number = mt_rand();
> I agree that "readonly" is a better keyword, but we have to points here:
> 1. "final" is used on some language (Java, C++ I guess);
> 2. "final" keyword does exists on PHP with a "similar" behaviour;
> If we can implements "readonly" is good too, because turn it more implicit.
True we could re-use the final keyword, but think about it this way,
we got final methods and final classes which means it cannot be
overridden/extended respectively, if the final keyword then would also
apply to variables but it would mean they could not be written to,
that would create a WTF-factor.
The readonly keyword would work for any visibility modifiers, so
inherited classes or extending classes may read a protected property,
but not modify it as well:
class A {
protected readonly $b;
public function __construct() {
$this->b = 'C';
}
}
class B extends A {
public function read() {
echo $this->b;
}
public function write() {
$this->b = 'D';
}
}
$b = new B;
$b->read(); // "C"
$b->write(); // <- error
--
regards,
Kalle Sommer Nielsen
kalle@php.net