Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 147 ยท Object-Oriented PHP

Readonly Properties and Immutable Objects

Learn PHP readonly properties and readonly classes, how to build immutable value objects with withers, clone and the PHP 8.5 clone-with syntax.

An immutable object never changes after it's created. If you want a different value, you make a new object. That sounds wasteful at first, but it removes a whole family of bugs: nobody can change your object behind your back, so you can pass it anywhere, store it, compare it and cache it without worrying about who else holds a reference to it.

PHP has supported this style for years by hand, with private properties and getters. Modern PHP makes it short and enforced: readonly properties (PHP 8.1) can be assigned exactly once, readonly classes (PHP 8.2) make every property readonly, and clone with (PHP 8.5) lets you copy an object while changing a few properties. This lesson covers all three and shows how to build proper value objects with them.

You'll want to know classes and properties and constructor property promotion first. A short reminder from those lessons: objects are passed around as handles, so $b = $a; gives you two variables pointing at the same object. That's exactly why immutability matters.

The problem: shared mutable objects

Here's a bug that immutability prevents. A function receives an object, changes it for its own purposes, and the caller's data changes too:

PHP A mutable object changed behind your back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both lines print 1200. The function returned the same object it received, so the original price is gone. In a small script you'd spot this. In a large application, where the price came from a cart that's also shown on another page, it's a nightmare to track down.

Readonly properties (PHP 8.1)

Add the readonly modifier to a property and PHP enforces two rules:

  1. The property can be initialized only once.
  2. It can be initialized only from inside the class (since PHP 8.4, also from child classes; see below).

After that, every write throws an Error:

PHP Readonly properties can be set once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is Error: Cannot modify readonly property Money::$cents followed by Cannot unset readonly property Money::$currency. The object really can't change.

The rules that come with readonly:

  • A readonly property must have a type. public readonly $x; is a compile error (Readonly property Q::$x must have type). Use mixed if you truly need any type.
  • It can't have a default value. public readonly int $x = 3; is a compile error. A readonly property with a fixed default would just be a constant, so use a class constant for that, or set it in the constructor.
  • It starts uninitialized. Reading it before the first assignment throws Typed property ... must not be accessed before initialization, like any typed property without a default.
  • Readonly only works on instance properties, not on static ones.

Where you can initialize it

The first assignment doesn't have to happen in the constructor; any method of the class can do it, once. That's useful for lazy values:

PHP Initializing a readonly property later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

isset() returns false for an uninitialized property without throwing, so it's the safe way to check. The second call reuses the stored value, and the outside write fails.

Since PHP 8.4, readonly properties are protected(set) by default rather than private(set), so a child class may initialize a readonly property declared by its parent. If you want the old strictness, declare it private(set) explicitly. Asymmetric visibility like this is the topic of the next lesson.

Readonly is shallow

readonly protects the property, not what's inside it. Arrays are values in PHP, so you can't append to a readonly array (Cannot indirectly modify readonly property). But if the property holds an object, the property always points at the same object, while that object's own state can still change:

PHP A readonly property holding a mutable object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The arrival date changed to 2026-07-11 even though the property is readonly, because DateTime::modify() changes the object in place. DateTimeImmutable::modify() returns a new object instead, so the departure stays 2026-07-05. For a truly immutable object, every property must hold an immutable value: scalars, arrays of scalars, enums, or other immutable objects. Prefer DateTimeImmutable over DateTime in general (see Dates and Times).

Readonly classes (PHP 8.2)

If every property of a class should be readonly, mark the class itself:

PHP
readonly class Coordinates
{
    public function __construct(
        public float $latitude,
        public float $longitude,
    ) {}
}

A readonly class makes every declared property readonly, and it adds one more rule: no dynamic properties ($coords->altitude = 5; throws Cannot create dynamic property Coordinates::$altitude). All properties must be typed, and static properties aren't allowed. Child classes of a readonly class must be readonly too.

Readonly classes are the most concise way to write data-transfer objects, configuration objects and value objects.

Changing an immutable object: withers

If an object can't change, how do you "update" it? You write methods that return a modified copy. By convention they're named with...(), hence the nickname withers. DateTimeImmutable has worked this way for years (setDate(), modify() and add() all return new objects).

Inside a method, you can't write to a readonly property of a clone... except in one place. Since PHP 8.3, readonly properties can be reinitialized inside __clone(). Before PHP 8.5 the usual wither was simply "build a new object with new static(...)". PHP 8.5 adds a much nicer tool.

clone with (PHP 8.5)

In PHP 8.5, clone can be called like a function, with a second argument: an array of property names and new values. PHP clones the object, then assigns those properties on the copy:

PHP Withers using clone with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$price still holds EUR 10.00 after every operation; each method hands back a fresh object. Compare this to the first example of the lesson: the bug simply can't happen anymore.

The property assignments in clone with follow normal visibility rules. They run in the scope where clone() is called, so from inside Money it can set the readonly properties, but code outside the class can't:

PHP
$hacked = clone($price, ['cents' => 1]);
// Error: Cannot modify protected(set) readonly property Money::$cents from global scope

That's why withers live inside the class. If a property is declared public public(set) readonly, outside code may set it through clone with too, which can make sense for plain data objects.

clone with assigns properties directly; it does not run the constructor. So the "Amount cannot be negative" check above is skipped: withCents(-5) would happily create a negative amount. If an invariant matters, validate in the wither too, or create the copy with new static(...). On properties that aren't readonly, a set hook (next lesson) validates every assignment, including the ones clone with makes.

Before PHP 8.5

You'll meet two older wither styles in existing code. The first creates a new object through the constructor, which also re-runs validation:

PHP
public function withCents(int $cents): static
{
    return new static($cents, $this->currency);
}

The second clones and changes the copy. With readonly properties this only works since PHP 8.3, and only inside __clone(), so it's awkward; libraries that support older versions use private non-readonly properties with getters instead. In new PHP 8.5 code, clone with replaces both.

Value objects

A value object is an immutable object defined entirely by its values: two Money(1000, 'EUR') objects mean the same thing, just as two integers 5 do. Value objects are a core idea in well-structured applications. Good candidates are money, email addresses, date ranges, coordinates, measurements, IDs and colors.

A value object typically:

  • is a final readonly class,
  • validates in the constructor, so an invalid instance can never exist,
  • offers withers and operations that return new instances,
  • has an equals() method that compares values, because === compares identity (see Comparing, Copying and Serializing Objects).
PHP An EmailAddress value object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This class doesn't use constructor promotion for $value, because it stores the normalized address rather than the raw argument. A readonly property can be assigned once anywhere in the constructor, after any validation you need.

Once a function accepts an EmailAddress instead of a string, it never has to validate or lower-case the email again. The type itself guarantees that the value is valid. This "make invalid states impossible" style is one of the OOP design principles that pays off most in real projects.

When not to use immutability

Immutability is a great default for values, but not for everything:

  • Entities with an identity and a lifecycle (a User that changes its name, an Order that moves through statuses) are often clearer as mutable objects with methods that enforce rules ($order->ship()).
  • Large collections that change constantly can be slow to copy over and over. Copying an object is cheap, but copying a big array inside it on every change adds up.
  • Framework objects such as ORM entities usually need to be mutable for the framework to work.

A good rule: if two objects with equal values are interchangeable, make it an immutable value object. If it has an identity that persists while its data changes, it's an entity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you run class A { public readonly int $x = 3; }?

    Readonly properties can't have default values. Use a class constant, or assign the value in the constructor.
  2. 2. A readonly property holds a DateTime object. What does $obj->date->modify("+1 day") do?

    readonly stops you from assigning a different value to the property, not from changing the object it points to. DateTime::modify() changes the object in place; use DateTimeImmutable for immutable dates.
  3. 3. Which statement about readonly classes (PHP 8.2) is true?

    A readonly class turns every declared property readonly, requires typed properties, and forbids creating dynamic properties.
  4. 4. Inside a method of a readonly class, what does return clone($this, ["cents" => 0]); do in PHP 8.5?

    clone with copies the object and then assigns the listed properties on the copy. The original is untouched, and the constructor doesn't run.
  5. 5. Two value objects new Money(100, "EUR") are created separately. What does === return when you compare them?

    === on objects checks identity, whether both variables point to the same instance. That's why value objects usually provide an equals() method.

Summary

  • Immutable objects never change; "modifying" one returns a new object. They prevent bugs caused by shared object handles.
  • readonly properties (8.1) must be typed, have no default, can be initialized once from inside the class, and throw Error on any later write or unset().
  • Readonly is shallow: a readonly property holding a mutable object (like DateTime) still lets that object change. Use immutable values all the way down.
  • readonly class (8.2) makes all properties readonly and forbids dynamic properties.
  • Withers (withCents()) return modified copies. In PHP 8.5, clone($this, ['prop' => $value]) does it in one line; it respects visibility and skips the constructor.
  • Value objects are final, readonly, validated in the constructor and compared with an equals() method.

Next: Property Hooks and Asymmetric Visibility