Immutability
suggest changeAn immutable value can't change after it has been created. To "modify" it you make a new value with the change applied and leave the original as it was.
PHP objects are passed around by handle, so any code holding an object can change it for everybody else. Immutable objects remove that whole class of bugs: you can pass them to any function, cache them or share them between services without wondering who changed what.
This article covers:
readonlyproperties (PHP 8.1) andreadonlyclasses (PHP 8.2)- the limits of
readonly: objects stored inside are still mutable - value objects, and "withers" that return modified copies
clonewith property overrides (PHP 8.5) and re-initializing readonly properties in__clone(PHP 8.3)DateTimeImmutablevsDateTime- asymmetric visibility (
private(set)) as a lighter alternative - immutable collections, enums and constants
- pitfalls: hooks, references, Reflection and serialization
Related topics: Properties, Constants, Enums, clone and DateTime class.
Readonly properties
A property marked readonly can be initialized once and never changed after that. Constructor property promotion makes this short:
<?php
final class Money
{
public function __construct(
public readonly int $amount,
public readonly string $currency,
) {}
}
$price = new Money(1999, 'USD');
echo $price->amount, ' ', $price->currency, "\n";
try {
$price->amount = 0;
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
unset($price->currency);
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
$price->amount++;
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
Output:
1999 USD
Error: Cannot modify readonly property Money::$amount
Error: Cannot unset readonly property Money::$currency
Error: Cannot modify readonly property Money::$amount
Reading is unrestricted. Any write after initialization (assignment, ++, unset()) throws an Error.
The rules:
- "Once" really means once, even inside the class. A method that assigns an already initialized readonly property fails too.
- Initialization must happen inside the class. Since PHP 8.4,
readonlyimpliesprotected(set), so child classes can initialize it as well, but outside code can't. - An unset readonly property is uninitialized. Reading it throws and
isset()returnsfalse.
<?php
final class User
{
public readonly string $name;
public function __construct(string $name)
{
$this->name = trim($name);
}
public function rename(string $name): void
{
$this->name = $name; // already initialized
}
}
$u = new User(' Alice ');
echo "[{$u->name}]\n";
try {
$u->rename('Bob');
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
final class Lazy
{
public readonly int $value;
}
$l = new Lazy();
var_dump(isset($l->value));
try {
echo $l->value;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
try {
$l->value = 42; // initializing from outside the class
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
[Alice]
Cannot modify readonly property User::$name
bool(false)
Typed property Lazy::$value must not be accessed before initialization
Cannot modify protected(set) readonly property Lazy::$value from global scope
Two compile-time restrictions are worth knowing. A readonly property must have a type (use mixed if you really need any value), and it can't have a default value. A default would leave nothing to initialize, so you'd want a constant instead:
class A {
public readonly $x; // Fatal error: Readonly property A::$x must have type
public readonly int $y = 5; // Fatal error: Readonly property A::$y cannot have default value
}
Static properties can't be readonly either.
Readonly classes
PHP 8.2 lets you put readonly on the class. Every declared property becomes readonly and dynamic properties are forbidden:
<?php
readonly class Point
{
public function __construct(
public float $x,
public float $y,
) {}
}
$p = new Point(1.5, 2.0);
try {
$p->x = 10;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
try {
$p->z = 3; // dynamic properties are forbidden too
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
$rc = new ReflectionClass(Point::class);
var_dump($rc->isReadOnly(), $rc->getProperty('x')->isReadOnly());
Output:
Cannot modify readonly property Point::$x
Cannot create dynamic property Point::$z
bool(true)
bool(true)
Inheritance has to agree. A readonly class can only extend, or be extended by, another readonly class:
readonly class Base {}
class Child extends Base {}
// Fatal error: Non-readonly class Child cannot extend readonly class Base
That's one reason value objects are usually declared final readonly class. If a subclass could add mutable state, the "immutable" guarantee wouldn't hold.
Readonly is shallow
readonly protects the property, meaning the value stored in it. What that value is decides how much protection you get.
- Scalars and arrays are values, so a readonly array is fully frozen. You can't even change one element in place.
- Objects are stored as handles. A readonly property holding an object stops you from swapping in a different object, but the object itself can still be changed.
<?php
readonly class Config
{
public function __construct(
public array $options,
public ArrayObject $cache,
) {}
}
$cfg = new Config(['debug' => false], new ArrayObject());
// arrays are values: no way to change the one stored in the property
try {
$cfg->options['debug'] = true;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
// but an object stored in a readonly property is still mutable
$cfg->cache['user:1'] = 'Alice';
echo count($cfg->cache), "\n";
// copying the array out and changing the copy doesn't affect the object
$opts = $cfg->options;
$opts['debug'] = true;
var_dump($cfg->options['debug']);
Output:
Cannot indirectly modify readonly property Config::$options
1
bool(false)
For a truly immutable object, every property should be a scalar, an array of immutable things, an enum, or another immutable object such as DateTimeImmutable. If you need to hold a mutable object, copy it when it comes in and copy it again before handing it out.
Value objects
A value object is defined by its data, not by identity. Two Money(500, 'USD') objects mean the same thing. Value objects are the main use for immutability in PHP. Operations return new instances instead of changing $this, and the constructor checks invariants once, so an invalid instance can never exist:
<?php
final readonly class Money
{
public function __construct(
public int $amount,
public string $currency,
) {
if ($amount < 0) {
throw new InvalidArgumentException("Amount can't be negative");
}
}
public function add(Money $other): static
{
$this->assertSameCurrency($other);
return new static($this->amount + $other->amount, $this->currency);
}
public function multiply(int $factor): static
{
return new static($this->amount * $factor, $this->currency);
}
public function equals(Money $other): bool
{
return $this->amount === $other->amount
&& $this->currency === $other->currency;
}
public function format(): string
{
return sprintf('%d.%02d %s', intdiv($this->amount, 100), $this->amount % 100, $this->currency);
}
private function assertSameCurrency(Money $other): void
{
if ($other->currency !== $this->currency) {
throw new LogicException("Currency mismatch: {$this->currency} vs {$other->currency}");
}
}
}
$price = new Money(1999, 'USD');
$shipping = new Money(500, 'USD');
$total = $price->multiply(3)->add($shipping);
echo $price->format(), "\n"; // unchanged
echo $total->format(), "\n";
var_dump($total->equals(new Money(6497, 'USD')));
var_dump($total == new Money(6497, 'USD')); // same class, equal properties
var_dump($total === new Money(6497, 'USD')); // different instances
try {
$price->add(new Money(100, 'EUR'));
} catch (LogicException $e) {
echo $e->getMessage(), "\n";
}
Output:
19.99 USD
64.97 USD
bool(true)
bool(true)
bool(false)
Currency mismatch: USD vs EUR
== compares objects of the same class property by property, which is often all you need for simple value objects. === checks identity, and that's rarely what you want for values. An explicit equals() method lets you decide what equality means, for example comparing case-insensitively or ignoring a cached field.
Withers: returning modified copies
When an object has many properties, calling the constructor in full for every change gets tedious. The usual pattern is a set of withX() methods (PSR-7 HTTP messages work like this). Each one returns a copy with a single property changed.
You might first try clone and then assign. That fails: outside __clone the copy's readonly properties are already initialized, so they can't be assigned again.
public function withMethod(string $method): static
{
$copy = clone $this;
$copy->method = $method; // Error: Cannot modify readonly property HttpRequest::$method
return $copy;
}
clone with property overrides (PHP 8.5)
PHP 8.5 turned clone into a function-like construct that takes an optional array of new property values. They're applied to the copy as part of cloning, so readonly properties can be set:
<?php
final readonly class HttpRequest
{
public function __construct(
public string $method = 'GET',
public string $url = '/',
public array $headers = [],
) {}
public function withMethod(string $method): static
{
return clone($this, ['method' => strtoupper($method)]);
}
public function withUrl(string $url): static
{
return clone($this, ['url' => $url]);
}
public function withHeader(string $name, string $value): static
{
return clone($this, [
'headers' => [...$this->headers, strtolower($name) => $value],
]);
}
}
$base = new HttpRequest(url: 'https://api.example.com');
$req = $base
->withMethod('post')
->withUrl('https://api.example.com/users')
->withHeader('Content-Type', 'application/json')
->withHeader('Accept', 'application/json');
echo $base->method, ' ', $base->url, ' ', count($base->headers), "\n";
echo $req->method, ' ', $req->url, "\n";
print_r($req->headers);
Output:
GET https://api.example.com 0
POST https://api.example.com/users
Array
(
[content-type] => application/json
[accept] => application/json
)
The overrides follow normal visibility rules. A plain public readonly property is protected(set), so clone($p, ['x' => 10]) works inside the class but fails from outside. To let callers use clone with directly, declare the property public public(set) readonly. It stays write-once on any existing object, but code anywhere can set it on a fresh clone:
<?php
final readonly class Point
{
public function __construct(public int $x, public int $y) {}
}
$p = new Point(1, 2);
try {
$q = clone($p, ['x' => 10]);
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
final class Point2
{
public function __construct(
public public(set) readonly int $x,
public public(set) readonly int $y,
) {}
}
$p2 = new Point2(1, 2);
$q2 = clone($p2, ['x' => 10]);
echo "$q2->x,$q2->y $p2->x,$p2->y\n";
try {
$q2->x = 5;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Cannot modify protected(set) readonly property Point::$x from global scope
10,2 1,2
Cannot modify readonly property Point2::$x
Note that clone with bypasses constructor validation. If a property has invariants, such as a non-negative amount, keep the wither inside the class and validate there, or build the copy with new static(...).
On PHP 8.1 to 8.4, withers that call the constructor work everywhere:
<?php
final class Temperature
{
public function __construct(public readonly float $celsius) {}
// virtual, get-only property: computed on every read, can't be set
public float $fahrenheit {
get => $this->celsius * 9 / 5 + 32;
}
// a "wither" that works on any PHP 8.1+: build a new object
public function withCelsius(float $celsius): static
{
return new static($celsius);
}
}
$t = new Temperature(20);
echo $t->fahrenheit, "\n";
echo $t->withCelsius(100)->fahrenheit, "\n";
try {
$t->fahrenheit = 50;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
68
212
Property Temperature::$fahrenheit is read-only
The $fahrenheit property uses a PHP 8.4 property hook with only a get and no backing value, so it's read-only by nature. Hooked properties can't be readonly, though, which means a class with hooks can't be a readonly class. That's why this example marks the individual property instead.
Deep copies in __clone (PHP 8.3)
clone makes a shallow copy, so the original and the copy share any objects they hold. Since PHP 8.3, readonly properties can be re-initialized inside __clone(), which lets you deep-copy mutable members:
<?php
final class Order
{
public function __construct(
public readonly string $id,
public readonly DateTime $createdAt, // mutable object!
) {}
public function __clone()
{
// PHP 8.3+: readonly properties may be re-initialized inside __clone
$this->createdAt = clone $this->createdAt;
}
}
$a = new Order('A-1', new DateTime('2026-01-15 10:00'));
$b = clone $a;
$a->createdAt->modify('+1 day'); // mutates the DateTime held by $a only
echo $a->createdAt->format('Y-m-d'), "\n";
echo $b->createdAt->format('Y-m-d'), "\n";
Output:
2026-01-16
2026-01-15
The better fix here is to store a DateTimeImmutable in the first place.
DateTimeImmutable vs DateTime
DateTime is the classic example of mutability causing bugs. Its modify(), add(), setTime() and similar methods change the object and return it, so the code reads as if it produced a new value:
<?php
function dueDate(DateTime $issued): string
{
return $issued->modify('+30 days')->format('Y-m-d');
}
$issued = new DateTime('2026-03-01');
echo dueDate($issued), "\n";
echo $issued->format('Y-m-d'), "\n"; // oops: the caller's date changed
Output:
2026-03-31
2026-03-31
DateTimeImmutable has the same API, but every method returns a new object:
<?php
$a = new DateTime('2026-01-31');
$b = $a->modify('+1 month'); // changes $a and returns it
echo $a->format('Y-m-d'), ' ', $b->format('Y-m-d'), ' ', var_export($a === $b, true), "\n";
$c = new DateTimeImmutable('2026-01-31');
$d = $c->modify('+1 month'); // returns a new object
echo $c->format('Y-m-d'), ' ', $d->format('Y-m-d'), ' ', var_export($c === $d, true), "\n";
$e = $c->setTime(9, 30)->add(new DateInterval('P2D'));
echo $e->format('Y-m-d H:i'), "\n";
// converting between the two
$mutable = DateTime::createFromImmutable($c);
$immutable = DateTimeImmutable::createFromMutable($a);
$fromInterface = DateTimeImmutable::createFromInterface($mutable);
echo get_class($immutable), ' ', $fromInterface->format('Y-m-d'), "\n";
Output:
2026-03-03 2026-03-03 true
2026-01-31 2026-03-03 false
2026-02-02 09:30
DateTimeImmutable 2026-01-31
Use DateTimeImmutable by default. Type parameters as DateTimeInterface when you accept either kind, and call DateTimeImmutable::createFromInterface() to get a value that's safe to keep.
Asymmetric visibility: read-only from outside
Sometimes an object has to change, but only through its own methods. PHP 8.4 asymmetric visibility (public private(set)) lets anyone read a property while only the class can write it, as many times as it needs. You don't have to write getters:
<?php
final class ShoppingCart
{
/** @var array<string, int> */
public private(set) array $items = [];
public private(set) int $version = 0;
public function add(string $sku, int $qty = 1): void
{
$this->items[$sku] = ($this->items[$sku] ?? 0) + $qty;
$this->version++;
}
}
$cart = new ShoppingCart();
$cart->add('apple', 3);
$cart->add('pear');
print_r($cart->items);
echo $cart->version, "\n";
try {
$cart->items = [];
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
try {
$cart->items['apple'] = 100;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Array
(
[apple] => 3
[pear] => 1
)
2
Cannot modify private(set) property ShoppingCart::$items from global scope
Cannot indirectly modify private(set) property ShoppingCart::$items from global scope
The object isn't immutable, but it's encapsulated. That's often the right choice for entities whose state really does change over time, while value objects stay readonly.
Immutable collections
PHP arrays are values with copy-on-write semantics. Passing an array to a function hands over a copy, as far as the caller can tell, so the function can't change the caller's array (unless it takes it by reference with &):
<?php
function addDefaults(array $config): array
{
$config['timeout'] ??= 30; // modifies the local copy only
return $config;
}
$config = ['host' => 'localhost'];
$full = addDefaults($config);
print_r($config);
print_r($full);
Output:
Array
(
[host] => localhost
)
Array
(
[host] => localhost
[timeout] => 30
)
A readonly array property is already immutable. A collection class adds a typed, chainable API. The class below implements ArrayAccess for $list[0] reads, and its write methods throw:
<?php
/**
* @template T
* @implements IteratorAggregate<int, T>
* @implements ArrayAccess<int, T>
*/
final readonly class ImmutableList implements IteratorAggregate, ArrayAccess, Countable
{
private array $items;
public function __construct(iterable $items = [])
{
$this->items = array_values([...$items]);
}
public function with(mixed $item): static
{
return new static([...$this->items, $item]);
}
public function without(int $index): static
{
$items = $this->items;
unset($items[$index]);
return new static($items);
}
public function map(callable $fn): static
{
return new static(array_map($fn, $this->items));
}
public function filter(callable $fn): static
{
return new static(array_filter($this->items, $fn));
}
public function toArray(): array
{
return $this->items;
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->items);
}
public function count(): int
{
return count($this->items);
}
public function offsetExists(mixed $offset): bool
{
return isset($this->items[$offset]);
}
public function offsetGet(mixed $offset): mixed
{
return $this->items[$offset] ?? throw new OutOfRangeException("No item at index $offset");
}
public function offsetSet(mixed $offset, mixed $value): never
{
throw new LogicException('ImmutableList cannot be modified; use with()');
}
public function offsetUnset(mixed $offset): never
{
throw new LogicException('ImmutableList cannot be modified; use without()');
}
}
$nums = new ImmutableList([1, 2, 3]);
$more = $nums->with(4)->with(5);
$evensSquared = $more->filter(fn($n) => $n % 2 === 0)->map(fn($n) => $n * $n);
echo implode(',', $nums->toArray()), "\n";
echo implode(',', $more->toArray()), "\n";
echo implode(',', $evensSquared->toArray()), "\n";
echo count($more), ' ', $more[0], ' ', $more->without(0)[0], "\n";
try {
$nums[] = 99;
} catch (LogicException $e) {
echo $e->getMessage(), "\n";
}
Output:
1,2,3
1,2,3,4,5
4,16
5 1 2
ImmutableList cannot be modified; use with()
toArray() returns the internal array safely, because the caller gets a copy.
Enums and constants
Enum cases are singletons whose name and value can't be changed, so they're a natural fit for fixed sets of options. Class constants (typed since PHP 8.3) are immutable by definition and may hold arrays:
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
public function label(): string
{
return ucfirst($this->value);
}
}
$s = Status::Draft;
try {
$s->value = 'x';
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
var_dump(Status::from('draft') === Status::Draft);
class Limits
{
public const int MAX_UPLOAD = 10 * 1024 * 1024;
public const array ALLOWED = ['jpg', 'png', 'webp'];
}
echo Limits::MAX_UPLOAD, ' ', implode('|', Limits::ALLOWED), "\n";
Output:
Cannot modify readonly property Status::$value
bool(true)
10485760 jpg|png|webp
See Enums and Class Constants for details.
Pitfalls and escape hatches
readonly is enforced by the engine. References and Reflection can't get around it once a property is initialized. There are still a few ways to create objects in unusual states:
<?php
final readonly class Token
{
public function __construct(public string $value) {}
}
$t = new Token('abc');
// references can't be taken to readonly properties
try {
$ref = &$t->value;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
// Reflection can't modify an initialized readonly property either
$prop = new ReflectionProperty(Token::class, 'value');
try {
$prop->setValue($t, 'hacked');
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
// ...but it can create an object without running the constructor
$blank = (new ReflectionClass(Token::class))->newInstanceWithoutConstructor();
$prop->setValue($blank, 'set once via reflection');
echo $blank->value, "\n";
// serialization round-trips readonly objects
$copy = unserialize(serialize($t));
var_dump($copy == $t, $copy === $t);
Output:
Cannot indirectly modify readonly property Token::$value
Cannot modify readonly property Token::$value
set once via reflection
bool(true)
bool(false)
Things to keep in mind:
unserialize(),newInstanceWithoutConstructor()and hydrators in ORMs and serializers skip the constructor, so its validation doesn't run. If the data comes from outside, validate it in__unserialize(), or call the constructor yourself.foreach ($obj->items as &$item)andsort($obj->items)both need a reference, so they fail on readonly arrays. Copy the array into a local variable first.- Lazy initialization in a getter (
$this->cache ??= compute()) works with readonly, because the first assignment counts as initialization. It only works from inside the class scope, though. - Each "modification" allocates a new object. That's cheap in PHP, but in a tight loop that builds up a large result, use a local mutable array and wrap it in an immutable object at the end.
Summary
readonlyproperties (PHP 8.1) can be initialized once, from inside the class. They must be typed and can't have defaults.readonly class(PHP 8.2) makes every property readonly and forbids dynamic properties. Pair it withfinalfor value objects.readonlyis shallow: arrays and scalars are frozen, but objects held in properties can still change. Store immutable objects such asDateTimeImmutable.- Return new instances instead of changing
$this: usenew static(...), PHP 8.5'sclone($this, [...]), or deep copies in__clone()(PHP 8.3+). - Prefer
DateTimeImmutabletoDateTime. - Use
public private(set)(PHP 8.4) for objects that must change but should be read-only to the outside world. - Enums, constants and arrays passed by value are immutable already.