readonly is now available in PHP 8.1, I just wonder what is the use of it? Is that to help the editor to know that this property is just readonly or to help the client to know that or there is another benefit?
readonly is now available in PHP 8.1, I just wonder what is the use of it? Is that to help the editor to know that this property is just readonly or to help the client to know that or there is another benefit?
readonly properties allow you to create immutable objects, or at the very least immutable properties.
That way you can be sure that a value won't be changed by accident after being initialized, throughout the object's life.
It's a very similar concept to constants (set via const or define), albeit with two important differences:
readonly properties will be set during runtime, usually during on object instantiation (so multiple instances will be able to hold different values*)You could achieve the same with a private property only accessible via a getter. E.g., in "the olden days":
class Foo {
private DateTimeImmutable $createAt;
public function __construct() {
$this->createdAt = new DateTimeImmutable();
}
public function getCreatedAt(): DateTimeImmutable
{
return $this->createdAt;
}
}
$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');
The only problem with this is that it requires a lot of boilerplate code.
With PHP 8.1. the same could be achieved by doing:
class Foo
{
public function __construct(
public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
)
{ }
}
$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')