Readonly Classes

Ma Mariya Vinciya Updated 21 Oct 2026
6 min read ·Lesson 169 of 174
In this post

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

  1. readonly class makes paise and currency readonly; the constructor initializes them once.
  2. Operations such as add() and percent() never change the object — they return a new Money. $price keeps its value no matter what happens to $tax or $total.
  3. Any attempt to change a property throws an Error.
  4. Validation in the constructor guarantees that every Money object is valid — and because it can never change, it stays valid.

Why Immutability Helps

BenefitExplanation
Safe sharingAn object can be passed to any function without fear that it will be modified
No defensive copiesNo need to clone before passing values around
Simpler reasoningA value checked once remains valid forever
Predictable caching and comparisonThe state never changes after creation

 


Rules for Readonly Classes

RuleConsequence
All properties are readonlyEach can be initialized only once, from inside the class scope
All properties must be typedUntyped properties cause a compile error
No static propertiesStatic state is not allowed in readonly classes
No dynamic propertiesCreating undeclared properties throws an Error; #[AllowDynamicProperties] cannot be used
InheritanceA 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:

VersionFeature
PHP 8.3Readonly properties can be re-initialized in __clone() (deep cloning)
PHP 8.3Anonymous classes can be readonly: new readonly class { ... }
PHP 8.5clone($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

SituationReason
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 cachesNot allowed
Frameworks that populate objects by setting properties after constructionSome 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer
Ask about this post
AI Ask about this post

Ask questions about Readonly Classes and get answers drawn from it.

Signed-in readers only.