readonly Properties (PHP 8.1)
TL;DR
PHP 8.1 readonly properties can only be written once (in the constructor) — enforcing immutability without verbose accessor boilerplate.
Explanation
public readonly string $name; cannot be written after initialization. Writing a second time throws Error. Cannot be unset. Must be typed. Cannot have a default value in declaration (except via constructor promotion). Combined with constructor promotion: public function __construct(public readonly string $name) — declare + promote + make readonly in one line. PHP 8.2 readonly classes: mark the entire class and all promoted properties are readonly. PHP 8.3 allows readonly property modification in __clone() for clone-with patterns. Use readonly for value objects, DTOs, request objects.
Common Misconception
✗ readonly prevents cloning with modifications — PHP 8.3 allows modifying readonly properties in __clone(). Before 8.3, use a with() method that returns a new instance.
Why It Matters
readonly eliminates the need for private property + public getter for immutable data — reducing boilerplate and enforcing value object immutability by the language.
Common Mistakes
- Trying to set readonly property after construction — throws Error.
- Forgetting readonly requires a type declaration.
- Not using readonly class (8.2) when all properties should be immutable.
Code Examples
✗ Vulnerable
class Money {
private int $amount;
private string $currency;
public function getAmount(): int { return $this->amount; }
public function getCurrency(): string { return $this->currency; }
}
✓ Fixed
// PHP 8.1 — readonly + constructor promotion:
class Money {
public function __construct(
public readonly int $amount,
public readonly string $currency,
) {}
}
// PHP 8.2 — readonly class:
readonly class Money {
public function __construct(
public int $amount,
public string $currency,
) {}
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
21
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Amazonbot 7
Unknown AI 3
Perplexity 3
ChatGPT 1
Google 1
Ahrefs 1
Also referenced
How they use it
crawler 14
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Low
⚡ Quick Fix
Add readonly to immutable properties. Combine with constructor promotion for concise value objects. Use readonly class (PHP 8.2) for fully immutable types.
📦 Applies To
PHP 8.1+
web
cli
queue-worker
🔍 Detection Hints
private \$[a-z].*getters
Auto-detectable:
✗ No
rector
phpstan
🤖 AI Agent
Confidence: Low
False Positives: High
✓ Auto-fixable
Fix: Medium
Context: Class