📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Readonly Properties

Readonly Properties

5 min read Quiz at the end
Readonly properties can only be set once in the constructor and cannot be changed after. This prevents accidental mutations and makes objects immutable. Great for value objects, DTOs, and configuration classes.

Readonly Properties (PHP 8.1)

class User {
    // Can only be set once (in constructor)
    public readonly int $id;
    public readonly string $email;

    public function __construct(int $id, string $email) {
        $this->id    = $id;
        $this->email = $email;
    }
}

$user = new User(1, "alice@example.com");
echo $user->id;     // 1
$user->id = 2;      // Error: Cannot modify readonly property!

// Readonly constructor promotion (PHP 8.1)
class Product {
    public function __construct(
        public readonly int    $id,
        public readonly string $name,
        public readonly float  $price,
    ) {}
}
Topic Quiz · 5 questions

Test your understanding before moving on

1. Readonly properties can be set:
💡 Readonly properties can only be initialized once — in the constructor.
2. What happens when you try to modify a readonly property?
💡 Attempting to modify a readonly property throws a fatal error.
3. Readonly properties were introduced in PHP:
💡 Readonly properties were introduced in PHP 8.1.
4. Can readonly properties have default values in their declaration?
💡 Readonly properties cannot have default values in declaration — they must be set in __construct.
5. Constructor promotion with readonly is:
💡 public readonly string $name in constructor parameters combines promotion and readonly.