Readonly Classes
What Is a Readonly Class? In simple terms: A readonly class is a class whose objects can never change after they are created. Every property is set once — usually in the constructor — and is locked fr
What Is a Readonly Class?
In simple terms: A readonly class is a class whose objects can never change after they are created. Every property is set once — usually in the constructor — and is locked from then on. It is the natural way to write value objects such as money amounts, coordinates, date ranges, or data passed between layers of an application.
Technically: Declaring a class with the readonly modifier (PHP 8.2+) makes every declared instance property readonly, as if each one were declared with readonly (see Readonly Properties). In addition, the class cannot have dynamic properties, untyped properties, or static properties.
Before and After
// PHP 8.1: readonly on every property
final class Coordinates
{
public function __construct(
public readonly float $latitude,
public readonly float $longitude,
) {}
}
// PHP 8.2+: readonly once, on the class
final readonly class Coordinates
{
public function __construct(
public float $latitude,
public float $longitude,
) {}
}
Both versions behave identically. The readonly class is shorter and guarantees that properties added later are readonly too — nobody can accidentally add a mutable property.
A Readonly Value Object
<?php
final readonly class Money
{
public function __construct(
public int $paise,
public string $currency = 'INR',
) {
if ($paise < 0) {
throw new InvalidArgumentException('Amount cannot be negative.');
}
}
public function add(Money $other): self
{
$this->assertSameCurrency($other);
return new self($this->paise + $other->paise, $this->currency);
}
public function percent(float $percent): self
{
return new self((int) round($this->paise * $percent / 100), $this->currency);
}
public function format(): string
{
return $this->currency . ' ' . number_format($this->paise / 100, 2);
}
private function assertSameCurrency(Money $other): void
{
if ($other->currency !== $this->currency) {
throw new InvalidArgumentException('Currency mismatch.');
}
}
}
$price = new Money(129900);
$tax = $price->percent(18);
$total = $price->add($tax);
echo "Price: " . $price->format() . "\n";
echo "GST: " . $tax->format() . "\n";
echo "Total: " . $total->format() . "\n";
try {
$price->paise = 1;
} catch (Error $e) {
echo $e->getMessage() . "\n";
}
Output
Price: INR 1,299.00
GST: INR 233.82
Total: INR 1,532.82
Cannot modify readonly property Money::$paise
How It Works
readonly classmakespaiseandcurrencyreadonly; the constructor initializes them once.- Operations such as
add()andpercent()never change the object — they return a newMoney.$pricekeeps its value no matter what happens to$taxor$total. - Any attempt to change a property throws an
Error. - Validation in the constructor guarantees that every
Moneyobject is valid — and because it can never change, it stays valid.
Why Immutability Helps
| Benefit | Explanation |
|---|---|
| Safe sharing | An object can be passed to any function without fear that it will be modified |
| No defensive copies | No need to clone before passing values around |
| Simpler reasoning | A value checked once remains valid forever |
| Predictable caching and comparison | The state never changes after creation |
Rules for Readonly Classes
| Rule | Consequence |
|---|---|
| All properties are readonly | Each can be initialized only once, from inside the class scope |
| All properties must be typed | Untyped properties cause a compile error |
| No static properties | Static state is not allowed in readonly classes |
| No dynamic properties | Creating undeclared properties throws an Error; #[AllowDynamicProperties] cannot be used |
| Inheritance | A readonly class can only be extended by a readonly class, and a readonly class cannot extend a non-readonly class |
| Methods, constants, interfaces, and traits (without properties that break the rules) | Allowed as usual |
Inheritance Example
readonly class Measurement
{
public function __construct(public float $value, public string $unit) {}
}
readonly class Temperature extends Measurement {} // allowed
// class MutableTemperature extends Measurement {} // compile error: must also be readonly
Many value objects are both final and readonly, which avoids inheritance questions entirely.
Readonly Is Shallow
Like readonly properties, a readonly class protects its own properties, not the objects they contain:
<?php
final readonly class Booking
{
public function __construct(
public string $guest,
public DateTime $checkIn,
) {}
}
$booking = new Booking('Asha', new DateTime('2026-10-20'));
$booking->checkIn->modify('+3 days'); // the DateTime object itself is mutable
echo $booking->checkIn->format('Y-m-d') . "\n";
Output
2026-10-23
The checkIn property still points to the same object, but that object was changed. To make the booking fully immutable, use immutable property types — here, DateTimeImmutable.
Creating Modified Copies
Because properties cannot be changed, "modifications" create new objects. The wither pattern names such methods with...():
<?php
final readonly class ShippingAddress
{
public function __construct(
public string $line1,
public string $city,
public string $pincode,
) {}
public function withPincode(string $pincode): self
{
return new self($this->line1, $this->city, $pincode);
}
}
$address = new ShippingAddress('12 Lake Road', 'Chennai', '600041');
$corrected = $address->withPincode('600042');
echo "{$address->pincode} → {$corrected->pincode}\n";
Output
600041 → 600042
Newer versions make copying easier:
| Version | Feature |
|---|---|
| PHP 8.3 | Readonly properties can be re-initialized in __clone() (deep cloning) |
| PHP 8.3 | Anonymous classes can be readonly: new readonly class { ... } |
| PHP 8.5 | clone($object, ['pincode' => '600042']) creates a modified copy in one step |
Readonly Data Transfer Objects
Readonly classes are also ideal for DTOs — objects that carry validated data between layers:
<?php
final readonly class CreateOrderCommand
{
public function __construct(
public int $customerId,
public array $items,
public string $paymentMethod,
public ?string $couponCode = null,
) {}
}
$command = new CreateOrderCommand(
customerId: 7,
items: [['sku' => 'PEN-01', 'quantity' => 3]],
paymentMethod: 'upi',
);
echo "Customer {$command->customerId}: " . count($command->items) . " line(s), pay by {$command->paymentMethod}\n";
Output
Customer 7: 1 line(s), pay by upi
Once a controller has created the command from validated request data, no service further down the line can alter it.
When Not to Use Readonly Classes
| Situation | Reason |
|---|---|
Entities whose state changes (an Order moving from "pending" to "paid") | Their purpose is to change over time |
| Objects built step by step (builders) | They need mutable state until they are complete |
| Classes needing static properties or caches | Not allowed |
| Frameworks that populate objects by setting properties after construction | Some ORMs and serializers need mutable properties |
Common Mistakes
Untyped Properties in a Readonly Class
Effect: Compile error.
Fix: Declare a type for every property.
Mixing Readonly and Non-Readonly Classes in a Hierarchy
Effect: Compile error when extending.
Fix: Make the whole hierarchy readonly, or make the class final.
Storing Mutable Objects
Effect: The object appears immutable but can still change.
Fix: Use immutable types (DateTimeImmutable, other readonly classes, arrays of scalars).
Trying to Change Values
Effect: Cannot modify readonly property.
Fix: Return new instances from with...() methods.
Best Practices
- Declare value objects and DTOs as
final readonly class. - Validate all data in the constructor; immutability keeps it valid.
- Use immutable types for every property.
- Implement changes as methods returning new instances.
- Keep entities and builders mutable where their behavior requires it.
Official reference: https\://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.readonly