Skip to content

Lesson 6 of 45 · Small Objects, Big Impact

Immutable Objects

Intermediate•
lesson•
October 11, 2026•
~10 min read

The bug class that disappears

You write a function that takes the stay dates for a reservation. Three function calls deep, somewhere you'll never look again, somebody writes $stay->checkOut = $stay->checkIn->addDay();.

Maybe it was deliberate. Maybe it was a debug line that didn't get removed. Maybe a refactor moved a side effect into a place nobody expected. Either way, the stay you handed in is not the stay you have now, and there's nothing in the type system that warned you.

This is the entire class of bugs that immutability removes. If the object can't be mutated after construction, the line above throws an Error the moment it runs, and PHPStan or your IDE flags it before that.

The Value Objects lesson introduced immutability as a property of value objects. This lesson takes the principle on its own and looks at the other places it earns its keep.

What "immutable" actually means

An immutable object is one whose state cannot change after the object is constructed. You set the values when you build it. You read them later. You can't write to them again.

If you need a different version, you don't mutate the existing object; you build a new one with the differences. The original stays untouched. Anyone who was holding it sees the same data they were holding before.

PHP gives you two tools for this. Readonly properties (PHP 8.1+) mark individual properties. They fit a class where some fields never change and others do, like an entity whose id is fixed but whose email can be updated:

PHP
<?php declare(strict_types=1); namespace App\Booking; final class Guest { public function __construct( public readonly GuestId $id, private EmailAddress $email, ) {} public function changeEmail(EmailAddress $email): void { $this->email = $email; } public function email(): EmailAddress { return $this->email; } }

Readonly classes (PHP 8.2+) make every property readonly automatically. They fit objects where nothing changes after construction, such as an event (trimmed here; the Domain Events lesson shows the full ReservationConfirmed):

PHP
<?php declare(strict_types=1); namespace App\Reservations; use DateTimeImmutable; final readonly class ReservationConfirmed { public function __construct( public ReservationId $reservationId, public DateTimeImmutable $confirmedAt, ) {} }

The second form is the one to default to for objects whose state never changes. final readonly class plus promoted properties says "this object's state is set at construction and never changes; nobody can extend this class to break that".

Where immutability earns its place

Small objects usually want to be immutable. Specifically:

  • Value objects. Already covered in the Value Objects lesson. The whole concept depends on immutability.

  • Data transfer objects. A data transfer object that gets mutated halfway through a use case is a debugging nightmare. The handler that received it sees one shape; the function it calls sees another. Lock them.

  • Commands. A command represents an intent: "request this reservation with these inputs". The intent doesn't change between dispatch and handling. Make commands final readonly.

  • Events. A domain event represents a fact about the past: "this reservation was confirmed at this time". Facts don't change. Mutation on an event is especially risky, because every listener reads it assuming it's stable.

  • Configuration. A config object loaded once at startup shouldn't be mutated by handlers down the line. If it can be, debugging "why is the config different in this request?" becomes a manhunt.

  • Results. A "result of running this calculation" object is a snapshot. If the result's fields can be reassigned, callers can't trust it.

  • Coordinates, identifiers, tokens. Anything that represents a thing rather than holds a thing. The thing isn't supposed to change identity.

Where it doesn't

A few cases where immutability is the wrong tool:

  • Long-running domain entities that genuinely evolve. A Reservation with a status that changes from pending to confirmed to cancelled, over a real lifecycle, is an entity. A later lesson will go deeper on this. Entities have identity and a history; their state changes by design. Immutable entities are theoretically possible (rebuild a new copy on every change) and almost always overkill in PHP.

  • Performance-critical loops. Building a new object every iteration in a hot loop has a cost. For pure value semantics, the cost is usually invisible. For very tight loops touching millions of items, a mutable accumulator is sometimes the right call.

  • Mutable collections. A ReservationCart that grows as rooms are added is fine. The cart is acting as a builder. Lock it once it crosses into the use case ($cart->finalize() returns an immutable object), but the buildup itself doesn't need to be immutable.

  • Framework-managed state. Eloquent models, Doctrine entities, sessions, and request-scoped containers all rely on mutation by design. Trying to make them immutable fights the framework rather than fitting it. Some libraries also depend on subclassing, so apply final readonly to the objects you control, especially the small ones flowing through your domain. The Active Record vs Data Mapper lesson gets into this.

Here's that cart. It stays mutable while the guest picks rooms, and finalize() hands the use case an object that can't change:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Booking\RoomId; final readonly class RoomSelection { /** @param list<RoomId> $roomIds */ public function __construct( public DateRange $stayDates, public array $roomIds, ) {} }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Booking\RoomId; use DomainException; final class ReservationCart { /** @var list<RoomId> */ private array $roomIds = []; public function __construct(private readonly DateRange $stayDates) {} public function addRoom(RoomId $roomId): void { $this->roomIds[] = $roomId; } public function finalize(): RoomSelection { if ($this->roomIds === []) { throw new DomainException('A reservation needs at least one room'); } return new RoomSelection($this->stayDates, $this->roomIds); } }

Rooms added after finalize() change the cart, not the RoomSelection the use case already holds. $roomIds is a readonly array of RoomId objects, which are immutable themselves, so it passes the array rule in the mistakes section below.

"How do I change an immutable object?"

You don't. You build a new one with the changes. The standard pattern is a with method. Here is DateRange, the stay dates of a reservation, in full:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Carbon\CarbonImmutable; use InvalidArgumentException; final readonly class DateRange { public function __construct( public CarbonImmutable $checkIn, public CarbonImmutable $checkOut, ) { if ($checkOut <= $checkIn) { throw new InvalidArgumentException('DateRange must end after it starts'); } } public static function ofNights(CarbonImmutable $checkIn, int $nights): self { return new self($checkIn, $checkIn->addDays($nights)); } public function nights(): int { return (int) $this->checkIn->diffInDays($this->checkOut); } public function overlaps(DateRange $other): bool { return $this->checkIn < $other->checkOut && $other->checkIn < $this->checkOut; } public function withCheckOut(CarbonImmutable $checkOut): self { return new self($this->checkIn, $checkOut); } }

$stay->withCheckOut($later) returns a new DateRange, identical to the original except for the check-out date. The original is still a valid range that anyone holding a reference to it can keep using. The caller can store the new one wherever it wants. Because the constructor validates, withCheckOut can't produce an invalid range either.

This pattern is sometimes verbose. From PHP 8.5, withCheckOut can be written as return clone($this, ['checkOut' => $checkOut]);, which copies the object and overrides the listed properties (readonly ones included, as long as the call happens inside the class, as it does here). It does not call the constructor, so the check-out validation would not run. The new self(...) form above works on every version and keeps the validation. The verbosity is the cost. The benefit is that nobody can ever silently change a DateRange out from under you.

The shared-state problem immutability solves

The deeper reason immutability matters is that mutable objects are shared state in disguise.

When you pass a mutable $price to three different services in sequence, you've handed all three the same object. The first one applies the weekly discount. The second one adds the city tax. The third one rounds it for display. The price at the end is the result of all three, and tracking down which one did what is your problem.

Here's the third service on its own. It rounds a quote to whole dollars for the price badge on the room page:

PHP
<?php declare(strict_types=1); namespace App\Pricing; final class Quote { public function __construct(public int $totalCents) {} }
PHP
<?php declare(strict_types=1); namespace App\Pricing; final class FormatQuoteForDisplay { public function format(Quote $quote): string { // Round to whole dollars for the price badge. $quote->totalCents = (int) round($quote->totalCents / 100) * 100; return '$' . number_format($quote->totalCents / 100); } }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Pricing\FormatQuoteForDisplay; use App\Pricing\Quote; final class ShowRoomPrice { public function __construct(private FormatQuoteForDisplay $formatter) {} /** @return array{label: string, charge_cents: int} */ public function handle(Quote $quote): array { $label = $this->formatter->format($quote); return ['label' => $label, 'charge_cents' => $quote->totalCents]; } }

A $185.50 quote shows as $186 on the badge, and charge_cents comes back as 18600. The formatter only meant to change what the guest sees, but it changed what the guest pays, and nothing in ShowRoomPrice hints at it.

When $price is an immutable Money, each service gets a price and returns a new one, the way applyDiscountPercent and add do. The formatter has to build its own rounded copy:

PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Billing\Money; final class FormatPriceForDisplay { public function format(Money $price): string { // Round to whole dollars for the price badge. $rounded = Money::fromCents( (int) round($price->amountInCents / 100) * 100, $price->currency, ); return $rounded->format(); } }

Writing to $price->amountInCents inside format() throws an Error, so the rounding can only happen on the copy. The caller's $price still holds 18550 cents. You decide which version becomes the price you store. The chain of who-did-what is explicit, in your code, not implicit, in memory.

That difference doesn't matter much in a short script. It matters a lot in a long-lived codebase where services, queue jobs, scheduled commands and event listeners all touch the same conceptual data.

A note on PHP's concurrency story

PHP is mostly single-threaded per request, which means a lot of the multi-threading horror stories about mutable state don't directly apply.

You will run code that keeps the same objects alive across more than one piece of work:

  • Async runtimes and libraries (Swoole, ReactPHP, Amp).

  • Long-lived processes that handle many requests in one PHP process (Octane, RoadRunner), where an object stored in a static property or a singleton survives from one request to the next.

In both settings, "this object got mutated by code on another path" is a real possibility, and finding it is hard. Immutable objects sidestep the question. They can be passed around, cached, and reused without anyone worrying about whether somebody else is editing them at the same time.

Common mistakes

A few things that look like immutability and aren't:

  • readonly on a property whose value is a mutable object. A readonly property holding an array (which is value-typed in PHP) is immutable, as long as the array holds scalars or immutable objects. A readonly property holding an ArrayObject or a mutable Carbon instance isn't. The reference can't change, but the object inside it can. Use CarbonImmutable over Carbon. Use plain array over mutable collection wrappers. Or wrap the mutable thing in a value object that controls access.

Here's the Carbon case. Every property is readonly, and the stay still moves:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Carbon\Carbon; final readonly class StayDates { public function __construct( public Carbon $checkIn, public Carbon $checkOut, ) {} }
PHP
<?php declare(strict_types=1); namespace App\Reservations; final class LateCheckOutOffer { public function offeredDate(StayDates $stay): string { return $stay->checkOut->addDay()->toDateString(); } }

offeredDate() returns 2026-05-13 for a stay ending on the 12th, and the stay now ends on the 13th too, because Carbon::addDay() changes the instance it's called on. Typing the properties as CarbonImmutable fixes it: addDay() then returns a new instance and leaves the stay alone.

  • final readonly plus a method that leaks a mutable object. A readonly property can't be reassigned, and a setter that tries throws an Error when called. But getInternalCart() returning a mutable Cart defeats the purpose, even if everything around it is readonly.

  • Public mutable arrays "for performance". "I'll just expose this array and let callers modify it." That's how shared-mutable-state bugs start. If callers need to add to it, they need a method that returns a new collection.

The one thing to remember

If you're not sure whether an object should be mutable, default to immutable. The cost is two modifiers, and an entire bug class disappears. If pain shows up later, relax the constraint then.

Course Content

Sign in to track your progress