×

php · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A property is written once, then locked for good.

Some values should never change once set: a ticket's seat, a payment's amount, a user's id. Mark a property readonly and PHP allows exactly one write, from inside the class. Any later change throws an Error, even from the class itself.

An object whose properties are all readonly is . Need a different value? Build a new object. A with method does this neatly: it returns a fresh copy with one thing changed and leaves the original alone, so nothing can surprise you later.

<?php
class Money {
    public function __construct(
        public readonly int $pence,
        public readonly string $currency,
    ) {}

    public function withPence(int $pence): self {
        return new self($pence, $this->currency);
    }
}
$price = new Money(250, "GBP");
$sale = $price->withPence(199);
echo "$price->pence $price->currency, now $sale->pence $sale->currency\n";

Readonly properties need a type, so write readonly int, never readonly on its own.