Readonly Classes (PHP 8.2)
Also Known As
PHP 8.2 readonly class
readonly class
TL;DR
Marking an entire class readonly automatically makes all its declared properties readonly, simplifying immutable value object creation.
Explanation
PHP 8.2 extended the readonly keyword from individual properties to entire class declarations. A readonly class implicitly makes all typed, non-static properties readonly — they can only be initialised in the constructor. This is ideal for DTOs, value objects, and command/query objects. Untyped properties are not allowed in readonly classes. Cloning a readonly object with modified properties requires clone with property initialisation syntax (PHP 8.3+ adds clone with syntax). Combining with constructor property promotion gives maximally concise immutable objects.
Common Misconception
✗ A readonly class is just a class where all properties happen to be readonly. Declaring a class readonly implicitly marks all properties readonly and prevents adding dynamic properties — it also clearly signals intent, helping static analysers enforce immutability contracts.
Why It Matters
PHP 8.2 readonly classes make all properties readonly by default — ideal for value objects and DTOs where immutability should be enforced without marking each property individually.
Common Mistakes
- Trying to use readonly classes with properties that need to change after construction — they are for immutable objects.
- Not knowing that readonly classes were added in PHP 8.2 — using the syntax on 8.1 causes a parse error.
- Adding mutable static properties to readonly classes — static properties are not affected by readonly.
- Cloning readonly class instances hoping to modify properties — clone creates an identical immutable copy.
Code Examples
✗ Vulnerable
class Point { public function __construct(
public readonly float $x,
public readonly float $y,
) {} }
✓ Fixed
readonly class Point { public function __construct(
public float $x,
public float $y,
) {} } // readonly on class covers all properties
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
27
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Amazonbot 9
Perplexity 6
Google 4
Unknown AI 2
Ahrefs 1
Also referenced
How they use it
crawler 19
crawler_json 3
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Add readonly before class to make all promoted and explicit properties readonly at once — perfect for DTOs, value objects, and query result types
📦 Applies To
PHP 8.2+
web
cli
queue-worker
🔍 Detection Hints
Class with all properties marked individually readonly when readonly class would cover them all; PHP 8.2+ project not using readonly classes for value objects
Auto-detectable:
✓ Yes
rector
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Class