Readonly properties are being added to PHP 8.1. Lets take a quick look at why that’s so great!

They work exactly the same as normal properties except that an error will be thrown if they’re set a second time. Traditionally getter methods get added to classes to allow other bits of code to use data from the object but prevent them messing it up by changing property values.

So a typical class might look something like this

<?php

class AppleTree
{
    private string $fruit;

    public function __construct()
    {
        $this->fruit = "Apple";
    }

    public function getFruit(): string
    {
        return $this->fruit;
    }
}

With readonly properties there’s no need for the getter method

<?php


class AppleTree
{
    public readonly string $fruit;

    public function __construct()
    {
        $this->fruit = "Apple";
    }
}

Code that uses this object can now access the property directly but is not able to change it’s value.

This might not seem like a huge deal but in the real world objects can have quite a few properties, not having write getters for all of them is going to cut down the number of methods and encourage more readable code.