Readonly Properties and Classes

6.Readonly Properties and Classes

M

In this chapter

We'll learn readonly properties, which can be set once and never changed, readonly classes, where every property is readonly, why immutable value objects like Money make prices safe, how to make a changed copy with PHP 8.5's clone with — and records and data classes from Java, Kotlin and C#, which PHP doesn't have as such.

13–15 min

The Problem in Real Life

Clare's booking was confirmed at £27.50, and her card was charged £27.50. Her invoice says £25.00. Mia finds the reason in a script that applies discounts: it loops over bookings and sets $booking->pricePence = 2500; — on bookings that were already confirmed and paid.

"A price that's been charged is a fact," says Marcus. "Facts don't change. The code shouldn't even be able to try."

O

Once a customer has paid a price, nothing in our system should be able to change it. Can we make that impossible?

Olivia

Values That Can Change vs. Values Set Once

Facts that change

A charged price, a booking's ID, a customer's sign-up date: some values must never change after they're set.

Set once, then locked

A readonly property can be set exactly once, inside the class. Every later write is an Error.

Change means a new value

To "change" an immutable price, you make a new Money object. The old one stays exactly as it was.

Readonly Properties and Classes

Immutability: an immutable value can't change after it's created. PHP has two tools for it:

  • readonly properties: set once, then locked.
  • readonly classes: every property readonly, for value objects like Money.
  • Changed copies: clone with new values, PHP 8.5's way of "changing" an immutable object.
  • Records and data classes: what Java, Kotlin and C# have, and how close PHP gets.

readonly properties: since PHP 8.1, a property marked readonly — public readonly int $pricePence; — can be assigned once, from inside the class (usually in the constructor), and never again. Any later assignment, from inside or outside, throws an Error: "Cannot modify readonly property Booking::$pricePence". Readonly properties must have a type, and they can't have a default value (that would be the "once"). They combine well with promotion: public function __construct(public readonly int $pricePence) {}. Since nobody can change them, they can safely be public: there's nothing to protect behind a getter.

Mia's bug, and readonly
<?php
declare(strict_types=1);
class PaidBooking
{
public function __construct(
public string $customer,
public readonly int $pricePence, // set once, in the constructor
) {}
}
$booking = new PaidBooking("Clare Lefèvre", 2750);
try {
$booking->pricePence = 2500; // the discount script
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
echo $booking->pricePence, "\n";
// Cannot modify readonly property PaidBooking::$pricePence
// 2750

Readonly classes and value objects: since PHP 8.2, readonly class Money { ... } makes every property of the class readonly. That's the shape of a value object: a small object that represents a value — an amount of money, a time slot, a phone number — and is defined only by that value. Two Money(2750) objects mean the same thing. Value objects are immutable on purpose: a price inside a confirmed booking can be passed to any function, logged, compared and stored, and nothing anywhere can change it. That's Olivia's wish, enforced by PHP.

A readonly value object: Money
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(public int $pence)
{
if ($pence < 0) {
throw new InvalidArgumentException("Money can't be negative");
}
}
public function format(): string
{
return "£" . number_format($this->pence / 100, 2);
}
}
$price = new Money(2750);
echo $price->format(), "\n"; // £27.50
var_dump($price == new Money(2750)); // bool(true): same value

"Changing" an immutable object: you don't. You create a new object with the new value, and the old one stays as it was: $discounted = $price->minus(250);. Inside the class, PHP 8.5's clone with makes that short: clone($this, ["pence" => $this->pence - 250]) copies the object and sets the given readonly properties on the copy, which is otherwise impossible after construction. (From outside the class it's refused, because readonly properties can only be written from inside.) This style — methods that return new objects instead of changing the old one — is how DateTimeImmutable works too, and why Laravel's dates are safe to pass around.

"Changing" an immutable object: a new one, with clone with (PHP 8.5)
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(public int $pence) {}
public function minus(int $pence): static
{
return clone($this, ["pence" => $this->pence - $pence]); // a copy with a new value
}
}
$price = new Money(2750);
$discounted = $price->minus(250);
echo $price->pence, " ", $discounted->pence, "\n"; // 2750 2500: the original is untouched
try {
clone($price, ["pence" => 0]); // from outside the class
} catch (Error $e) {
echo "Refused from outside\n"; // Refused from outside
}

Readonly is shallow: readonly locks the property, not everything reachable through it. A readonly property holding an array can't be changed at all (not even $x->items[] = ...), because an array is a value. But a readonly property holding an object only stops you from replacing that object; the object's own properties can still change, unless its class is readonly too. Build value objects from scalars and other value objects, and they're immutable all the way down.

Readonly is shallow
<?php
declare(strict_types=1);
class Customer
{
public function __construct(public string $phone) {}
}
final readonly class Booking
{
public function __construct(public Customer $customer, public array $services) {}
}
$booking = new Booking(new Customer("+447700900456"), ["Haircut"]);
$booking->customer->phone = "+447700900999"; // allowed: Customer itself isn't readonly
echo $booking->customer->phone, "\n"; // +447700900999
try {
$booking->services[] = "Hot towel"; // not allowed: the array is part of the property
} catch (Error $e) {
echo $e->getMessage(), "\n"; // Cannot indirectly modify readonly property Booking::$services
}

Records and data classes — not as such in PHP: several languages have a dedicated keyword for small immutable data types. Java has record (Java 16), Kotlin has data class, and C# has record. With one line, they generate the constructor, read-only fields, an equals() that compares values, a readable toString(), and (in Kotlin and C#) a way to make a changed copy. PHP doesn't have a record type. Its closest equivalent is a final readonly class with constructor property promotion, which gives you the constructor and the immutable fields; == already compares objects by their property values (chapter 13), and clone with gives you changed copies. What you write yourself is the rest: methods like equals() or __toString() (Act 12). The table below compares them.

Table — Immutable data types compared
NeedPHPJava / Kotlin / C#
One immutable propertypublic readonly int $pence (8.1)final (Java), val (Kotlin), init/readonly (C#)
Every property immutablereadonly class (8.2)record / data class
Generated constructorConstructor property promotionGenerated by record / data class
Compare by value== compares property valuesGenerated equals()
Readable text formWrite __toString() yourself (Act 12)Generated toString()
A changed copyclone($this, [...]) inside the class (8.5)copy() (Kotlin), with (C#)
Kotlin: a data class (not in PHP as such)
// Kotlin — one line generates constructor, equals(), toString() and copy()
data class Money(val pence: Int)
val price = Money(2750)
val discounted = price.copy(pence = 2500)
println(price == Money(2750)) // true
println(discounted) // Money(pence=2500)

Key Takeaway

A readonly property (PHP 8.1) can be set once, from inside the class, and never changed; it must be typed and has no default. A readonly class (PHP 8.2) makes every property readonly — the right shape for value objects like Money. To "change" an immutable object, return a new one; inside the class, PHP 8.5's clone($this, [...]) makes a changed copy. Readonly is shallow for objects inside. PHP has no record or data class keyword; final readonly class with promotion is the closest equivalent.

Why This Matters

Money that can change behind your back is how invoices and charges stop matching. With readonly value objects, a price that has been calculated, shown and charged stays exactly that price everywhere it travels — PHP itself refuses every attempt to change it.

Immutable objects are also easier to reason about: you never have to ask "did some other code change this?". That's why modern PHP and Laravel code uses readonly for value objects, data transfer objects and configuration.

Prices are Money objects now, and a paid booking's price is readonly. Then Olivia adds a new kind of booking: group bookings for stag parties, with a group discount. Mia copies the 120-line Booking class into GroupBooking and edits it. A week later, a fix to Booking::confirm() reaches ordinary bookings — and not group ones. That's the next chapter: inheritance.