If you regularly read the blog, you probably know that I like to write strongly typed code wherever possible, and use static analysis wherever I can.
You can imagine how happy I was when I first saw the readonly properties RFC pop-up for PHP 8.1: once again a feature that helps me write cleaner, properly typed code.
PHP 7.4 already gave us typed properties,
PHP 8.0 introduced promoted properties
and now we get readonly properties. Awesome!Maybe a quick explainer is warranted about what readonly properties are: they are an easy way to only allow a property value to be set once, and prohibit any changes to them from that point on. They are a great way to model value objects and data-transfer objects, which I use quite a lot!
Ok, that's enough rambling, let's get on with readonly properties!
Let me show you the difference it makes when all these features are combined. This is what a (simplified) DTO would look like before PHP 7.4:
class BlogData
{
/** @var string */
private $title;
/** @var State */
private $state;
public function __construct(
string $title,
State $state
) {
$this->title = $title;
$this->state = $state;
}
public function getTitle(): string
{
return $this->title;
}
public function getState(): State
{
return $this->state;
}
}
PHP 7.4 added typed properties
allow us to ditch the doc blocks:class BlogData
{
private string $title;
private State $state;
public function __construct(
string $title,
State $state
) {
$this->title = $title;
$this->state = $state;
}
public function getTitle(): string
{
return $this->title;
}
public function getState(): State
{
return $this->state;
}
}
Next
PHP 8.0 added constructor property promotion
which allowed us to shorten our code even further:class BlogData
{
public function __construct(
private string $title,
private State $state,
) {}
public function getTitle(): string
{
return $this->title;
}
public function getState(): State
{
return $this->state;
}
}
And now, finally, there's readonly properties as well, having the most significant impact of all:
class BlogData
{
public function __construct(
public readonly string $title,
public readonly State $state,
) {}
}
I guess you'd understand when I tell you that readonly properties are my personal favourite feature of PHP 8.1.