Readonly Classes

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 186 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

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

Signed-in readers only.