PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
23: Readonly Properties
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 readonlyproperties:string $trackingNumber,string $destinationAddress, andfloat $weight. - In your main script, instantiate the
OrderManifestwith sample data. - Print the tracking number to the screen to verify it works.
- Uncomment a line of code that attempts to change the
destinationAddressand observe theFatal errorthat 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';
?>
There are no comments for now.