Readonly Property in PHP: What It Is and How It Works
readonly property in PHP is a class property that can only be assigned once, typically during object creation. After it is set, its value cannot be changed, making the property immutable and helping to prevent accidental modifications.How It Works
Think of a readonly property like a sealed box that you can put something into only once. After you close the box, you cannot change what is inside. In PHP, when you declare a property as readonly, you allow it to be set only once, usually when the object is created.
This means you can assign a value to the property in the constructor or at the point of declaration, but any later attempt to change it will cause an error. This helps keep your data safe and consistent, especially when you want to make sure certain values never change after being set.
Example
This example shows a class with a readonly property. The property is set in the constructor and cannot be changed later.
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Alice"); echo $user->name . "\n"; // Uncommenting the next line will cause an error because the property is readonly // $user->name = "Bob";
When to Use
Use readonly properties when you want to create objects with values that should never change after they are set. This is useful for things like configuration settings, user IDs, or any data that must remain constant to avoid bugs.
For example, if you have a class representing a product with a fixed SKU code, marking the SKU as readonly ensures it cannot be accidentally modified later in the program.
Key Points
- Readonly properties can only be assigned once.
- They are typically set in the constructor.
- Trying to change them later causes an error.
- They help make objects immutable and safer.
- Available since PHP 8.1.