Exploring the Advantages of PHP 8.1’s Readonly Feature

ReadOnly properties differ from regular properties in that they cannot have a predefined value in their definition. By using readonly properties in combination with constructor property promotion, you can reduce boilerplate code and create useful classes more efficiently. Additionally, the use of readonly properties can enhance code clarity and more accurately convey your intentions.


With the use of properties in


, it becomes possible to design objects that are immutable or at least have immutable attributes.

This approach ensures that a value remains unchanged once it has been initialized, thus preventing any accidental changes throughout the lifespan of the object.

The idea is closely akin to constants, which can be established through




. However, there are two notable distinctions.

  • Constants are established at “compilation” time, whereas


    properties are typically assigned when an object is instantiated during runtime. This allows for multiple instances to hold varying values.
  • Unlike constants that exist in the global scope, class constants are linked to the class itself, rather than to any instance.

A private property, exclusively accessible through a getter, could yield the same outcome as mentioned previously, for instance, in the past.

class Foo {
    private DateTimeImmutable $createAt;
    public function __construct() {
        $this->createdAt = new DateTimeImmutable();
    public getCreatedAt(): DateTimeImmutable
        return $this->createdAt;
$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');

The downside is that it necessitates a significant amount of repetitive code.

It is possible to accomplish the same thing with PHP 8.1 through the following method:

class Foo
    public function __construct(
        public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
    { }
$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')

Frequently Asked Questions

Posted in Php