๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Readonly Properties

A readonly property is a property that can be written one time only. After that first write, its value stays fixed for the life of the object.

Promoted readonly properties print

The Point class promotes two readonly properties in its constructor. The constructor write is the one write each property ever gets, and both values print.

<?php
class Point {
  public function __construct(
    public readonly int $x,
    public readonly int $y
  ) {
  }
}
$p = new Point(3, 4);
echo $p->x . "\n";
echo $p->y . "\n";

A plain readonly property written once inside

The Token class declares a plain readonly property with no value. The constructor writes it one time, and the stored code prints.

<?php
class Token {
  public readonly string $code;
  public function __construct() {
    $this->code = "A42";
  }
}
$t = new Token();
echo $t->code . "\n";

A readonly class locks every property

The Size class carries the readonly word on the class itself. Neither property repeats the word, and both values still print as fixed values.

<?php
readonly class Size {
  public int $width;
  public int $height;
  public function __construct(int $width, int $height) {
    $this->width = $width;
    $this->height = $height;
  }
}
$s = new Size(10, 4);
echo $s->width . "\n";
echo $s->height . "\n";

A write from outside fails

The last line tries to change $x from outside the class. PHP refuses the write with a fatal error, and the stated line is the whole real error line.

<?php
class Point {
  public function __construct(
    public readonly int $x,
    public readonly int $y
  ) {
  }
}
$p = new Point(3, 4);
$p->x = 9;

Example

<?php
class Money {
  public function __construct(
    public readonly int $cents,
    public readonly string $code
  ) {
  }
}
$m = new Money(1250, "USD");
$dollars = intdiv($m->cents, 100);
$rest = $m->cents % 100;
echo $m->code . " " . $dollars . "." . $rest . "\n";

Key points

  • The readonly word sits before the type in a property declaration.
  • A readonly property can be written only from inside its own class.
  • A promoted constructor property can carry the readonly word too.
  • A readonly class makes every property in it readonly at once.
  • Readonly properties suit value objects that must never change after they are built.

In this example, Money is a small value object with two promoted readonly properties. intdiv takes the whole dollars from the cents, and the remainder operator takes the leftover cents. One line joins the code and the two parts into a price.

Note

Reading a readonly property from outside the class is free, and only the write is locked.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When can a readonly property be written?