TExcelTAD
Home › PHP › PHP Readonly Properties

PHP Readonly Properties

Some values should never change after an object is created: the ID of an order, the coordinates of a point, the amount of a payment. Before PHP 8.1 you protected them with private properties plus getter methods. Now you can mark a property readonly: it can be assigned once, from inside the class, and after that any attempt to change it throws an Error.

Declaring readonly properties

php · try it yourself
<?php
class Point
{
    public readonly float $x;
    public readonly float $y;

    public function __construct(float $x, float $y)
    {
        $this->x = $x;
        $this->y = $y;
    }
}

$p = new Point(3, 4);
echo "($p->x, $p->y)\n";

try {
    $p->x = 10;
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

echo "x is still $p->x\n";
(3, 4)
Cannot modify readonly property Point::$x
x is still 3

The property is public, so anyone can read it, but nobody can overwrite it.

With constructor promotion

Readonly works great with constructor property promotion, giving very compact immutable classes:

php · try it yourself
<?php
class Payment
{
    public function __construct(
        public readonly string $id,
        public readonly int $amountCents,
        public readonly string $currency = 'EUR',
    ) {}

    public function formatted(): string
    {
        return number_format($this->amountCents / 100, 2) . " " . $this->currency;
    }
}

$pay = new Payment("PAY-7781", 4599);
echo $pay->id, ": ", $pay->formatted(), "\n";

try {
    $pay->amountCents = 1;
} catch (Error $e) {
    echo "Blocked: ", $e->getMessage(), "\n";
}
PAY-7781: 45.99 EUR
Blocked: Cannot modify readonly property Payment::$amountCents

The rules

Rule Detail
Typed only A readonly property must have a type (readonly int $n, not readonly $n)
Assigned once The first assignment initialises it; any later write throws Error
From inside Initialisation must happen in the declaring class's scope (PHP 8.4 relaxes this slightly for child classes)
No default value public readonly int $n = 5; is not allowed — set it in the constructor
No unset after init You cannot unset an initialised readonly property
Not static Static properties cannot be readonly

Reading a readonly property before it is initialised also throws an Error:

php · try it yourself
<?php
class Lazy
{
    public readonly string $token;

    public function init(string $t): void
    {
        $this->token = $t;
    }
}

$l = new Lazy();

try {
    echo $l->token;
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

$l->init("abc123");
echo $l->token, "\n";

try {
    $l->init("again");
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}
Typed property Lazy::$token must not be accessed before initialization
abc123
Cannot modify readonly property Lazy::$token

Readonly classes

Since PHP 8.2 you can put readonly in front of the whole class. Every declared property then becomes readonly automatically, and dynamic properties are forbidden.

php · try it yourself
<?php
final readonly class Money
{
    public function __construct(
        public int $cents,
        public string $currency,
    ) {}

    // "withers" return a modified copy instead of changing $this
    public function add(int $cents): static
    {
        return new static($this->cents + $cents, $this->currency);
    }
}

$price = new Money(1000, 'USD');
$withTax = $price->add(80);

echo $price->cents, " -> ", $withTax->cents, " ", $withTax->currency, "\n";

try {
    $price->currency = 'EUR';
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}
1000 -> 1080 USD
Cannot modify readonly property Money::$currency

This "return a new object" style is called an immutable design. Immutable objects are easy to reason about: once you hold one, you know no other code can change it behind your back.

Tip: Readonly is shallow. If a readonly property holds an object, you cannot replace that object, but the object itself can still change its own (non-readonly) properties. Arrays, on the other hand, are values — you cannot even append to a readonly array.

Cloning readonly objects

clone copies the readonly values, but in PHP 8.4 you still cannot change them on the copy from outside. The usual pattern is the "wither" method shown above, which builds a fresh object with new static(...). (PHP 8.3 also allows re-initialising readonly properties inside __clone().)

Note: Use readonly for value objects, DTOs (data transfer objects), configuration and events. Keep ordinary mutable properties for things that genuinely change over time, such as a shopping cart's item list.

Test yourself

What happens when code tries to change an already-initialised readonly property?

  1. The new value is silently ignored
  2. A warning is printed and the value changes
  3. An Error is thrown
  4. The object is cloned

Which declaration is valid?

  1. public readonly $name;
  2. public readonly string $name = 'x';
  3. public readonly string $name;
  4. public static readonly int $n;

What does readonly class Point { ... } do?

  1. Makes the class impossible to instantiate
  2. Makes every declared property readonly
  3. Makes all methods final
  4. Prevents inheritance only