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,
) {}
}