CodeBlanks Logo Icon CodeBlanks

readonly property

PHP course · Expert · Lesson 36/54

Learn properties that can be written only once with readonly property.

What is a readonly property?

The readonly keyword, added in PHP 8.1, marks a property so it can be written only once. After the first assignment it cannot be changed.

This is ideal for value objects whose value must stay constant for their lifetime. It removes the risk of accidental later modification.

A readonly property is declared together with its type and must be given an initial value.

Constructor property promotion and readonly class

PHP 8.0 introduced constructor property promotion: declare properties directly in the constructor parameter list, e.g. public function __construct(public readonly float $x).

PHP 8.2 adds readonly class. Marking a class readonly makes every property readonly automatically; no need to repeat the keyword.

Combine the two to write immutable value objects in just a few lines.

Exercise Immutable Money class

Write an immutable Money class. Declare it as a readonly class and define $amount (int) and $currency (string) properties using constructor property promotion.

The creation and echo lines below should print 100.

Show example solution
readonly class Money {
  public function __construct(
    public readonly int $amount,
    public readonly string $currency
  ) {}
}

$m = new Money(100, "TRY");
echo $m->amount;

Test yourself

  1. When can you write to a readonly property?

    class Point {
        public function __construct(
            public readonly float $x
        ) {}
    }
    
    $p = new Point(3.5);
    // can we change $p->x after this?
    • Only inside the constructor of the declaring class
    • From anywhere, at any time
    • Only from static methods
    • From subclasses at any time
    Show answer

    Only inside the constructor of the declaring class — Correct. A readonly property may be assigned only inside the constructor of the declaring class; then it freezes.

  2. readonly with constructor property promotion

    class Point {
      public function __construct(
        public ____ float $x,
        public readonly float $y
      ) {}
    }
    Show answer
    class Point {
      public function __construct(
        public readonly float $x,
        public readonly float $y
      ) {}
    }
  3. What does a readonly class do?

    • It prevents inheritance of the class
    • It hides the class properties
    • It makes all properties readonly automatically
    • It makes the class abstract
    Show answer

    It makes all properties readonly automatically — Correct. A readonly class makes all its properties readonly automatically; no need to repeat the keyword on each.

All lessons in Expert