before Php 8.1 we could wrote that:
abstract class Base
{
private $thing;
public function __construct($thing)
{
$this->thing = $thing;
}
protected function getThing()
{
return $this->thing;
}
}
class Test1 extends Base
{
private function needThing()
{
... $this->getThing();
}
}
class Test2 extends Base
{
private function needThing()
{
... $this->getThing();
}
}
so getThing() was to get the inner thing object.
It could have been written like that:
abstract class Base
{
protected $thing;
public function __construct($thing)
{
$this->thing = $thing;
}
}
class Test1 extends Base
{
private function needThing()
{
... $this->thing;
}
}
class Test2 extends Base
{
private function needThing()
{
... $this->thing;
}
}
it's shorter, does the same, but not $thing isn't really protected, it can be read and modified (the first example at least prevented from modifing).
But here comes the readonly modifier:
abstract class Base
{
readonly private $thing;
public function __construct($thing)
{
$this->thing = $thing;
}
protected function getThing()
{
return $this->thing;
}
}
class Test1 extends Base
{
private function needThing()
{
... $this->thing;
}
}
class Test2 extends Base
{
private function needThing()
{
... $this->thing;
}
}
I think this is a serious game changer, makes a lot of getters futile. Of course it looks you're reaching a tag variable, but still acts like a method, once it was written (in constructor) and now no longer possible to overwrite.
So, can "readonly" replace protected get-ters?