Cannot Modify Readonly Property
Fatal error: Uncaught Error: Cannot modify readonly property App\Entity\User::$emailQuick Answer
You are trying to change a readonly property after it has been initialized. Readonly properties can only be set once, in the constructor. Create a new object with the updated value instead.
Why This Happens
PHP 8.1 introduced readonly properties that can only be assigned once during initialization. After the constructor sets a readonly property, any attempt to modify it throws this error. This enforces immutability for specific properties.
The Problem
class User {
public function __construct(
public readonly string $email
) {}
}
$user = new User('old@example.com');
$user->email = 'new@example.com'; // Cannot modify readonlyThe Fix
class User {
public function __construct(
public readonly string $email
) {}
public function withEmail(string $email): self {
return new self($email);
}
}
$user = new User('old@example.com');
$user = $user->withEmail('new@example.com');Step-by-Step Fix
- 1
Understand readonly semantics
Readonly properties are intentionally immutable. They can only be set in the class constructor or property declaration.
- 2
Use a wither method
Create a method that returns a new instance with the modified value, following the immutable object pattern.
- 3
Remove readonly if mutability is needed
If the property genuinely needs to change after construction, remove the readonly modifier and add validation in a setter instead.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free