Skip to Content
Course content

23: Readonly Properties

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once spent an entire Friday afternoon hunting for a bug in a payment processing pipeline. We had a Transaction object that carried the transactionId and amount through several different services. Somewhere in a "helper" method designed to format the currency for a log file, a developer had accidentally used an assignment operator (=) instead of a comparison operator (==). This silently changed the transaction ID mid-request, and suddenly, we were updating the wrong records in the database. It was a classic case of "unintended mutation."

In older versions of PHP, the only way to prevent this was to make the property private and write a public getter method. It worked, but it added a ton of boilerplate code that felt tedious to write and maintain. That's why readonly properties, introduced in PHP 8.1, are such a breath of fresh air. They allow you to keep a property public—so you can access it easily—while guaranteeing that it can never be changed once it has been initialized.

Stopping the Accidental Mutation

When you mark a property as readonly, you're telling PHP that this value is set once and then frozen. If any part of your code tries to modify that property after it's been assigned, PHP will throw a Error immediately. This turns a silent, nightmare-inducing bug into a loud, easy-to-fix crash.

class PaymentTransaction {
    public readonly string $transactionId;
    public readonly float $amount;

    public function __construct(string $id, float $amt) {
        $this->transactionId = $id;
        $this->amount = $amt;
    }
}

$tx = new PaymentTransaction('TXN-123', 49.99);
echo $tx->transactionId; // Works fine

$tx->transactionId = 'TXN-456'; // Fatal error: Cannot modify readonly property

Notice that I used public readonly. This is the "magic" part. I don't need a getTransactionId() method anymore. I can just grab the property directly, but I have the peace of mind knowing that no one—not even a rogue helper method—can change it.

Streamlining with Constructor Promotion

If you're using readonly, you're almost certainly going to use it alongside constructor promotion. If you remember from previous lessons, constructor promotion lets us declare properties directly in the constructor signature. Combining these two features allows you to create "Data Transfer Objects" (DTOs) in a single line of code.

class UserProfile {
    public function __construct(
        public readonly int $userId,
        public readonly string $email,
        public readonly string $username,
    ) {}
}

$user = new UserProfile(101, 'dev@example.com', 'php_pro');

I use this pattern constantly. It removes the need to declare the property at the top of the class and then assign it inside the curly braces. It's concise, readable, and explicitly communicates that this object is meant to be an immutable snapshot of data.

The Nuances of Initialization

One thing you need to keep in mind: a readonly property must be initialized before it is accessed. If you try to read a readonly property that hasn't been set yet, PHP will throw an Error. This is different from a regular property, which would just return null or a default value.

Also, remember that readonly is not the same as a const. A constant is the same for every single instance of a class. A readonly property is different for every instance, but once that specific instance is set, it stays that way. I usually reach for readonly when the value is determined at runtime (like a database ID) rather than at design time (like a mathematical constant).




📋 Practical Task

Build an Immutable Order Manifest

You are building a shipping system. You need to create a class called OrderManifest that ensures critical shipping details cannot be altered once the manifest is created. This prevents the shipping label from being changed after the package has been processed.

Requirements:

  • Create a class OrderManifest.
  • Use constructor promotion to define three public readonly properties: string $trackingNumber, string $destinationAddress, and float $weight.
  • In your main script, instantiate the OrderManifest with sample data.
  • Print the tracking number to the screen to verify it works.
  • Uncomment a line of code that attempts to change the destinationAddress and observe the Fatal error that PHP throws.
<?php
// Your OrderManifest class here

// Test the class
$manifest = new OrderManifest('XYZ12345', '123 PHP Lane, Web City', 2.5);
echo "Tracking: " . $manifest->trackingNumber;

// This should trigger a Fatal Error:
// $manifest->destinationAddress = '456 Bug Street, Error Town';
?>
Rating
0 0

There are no comments for now.

to be the first to leave a comment.