PHP Readonly Classes vs Readonly Properties for DTOs
Choose between PHP 8.2 readonly classes and PHP 8.1 readonly properties for immutable DTOs, with validation steps.
27 Nov 2026, 07:45 UTC

The problem: mutable data moves through your application
PHP applications often pass data between layers using arrays or stdClass objects. Both are mutable by default, which means any service, template, or middleware that receives the data can change its values without the original author knowing. A data transfer object (DTO) is a plain object used to carry data between application layers. When that object is mutable, bugs become harder to trace because state can change anywhere.
Useful takeaway: on PHP 8.2 or later, prefer a readonly class when every field in a DTO should stay fixed after construction. Use individual readonly properties when you need a mix of immutable and mutable fields. Avoid arrays and stdClass for domain payloads.
Decision constraints
readonly classrequires PHP 8.2 or later.readonlyproperties require PHP 8.1 or later.- Readonly properties must be typed; untyped
readonlyproperties are not allowed. - Readonly properties cannot be
static. - After initialization, a readonly property cannot be unset or reassigned.
- A
readonly classmakes every declared property readonly implicitly.
Supported options compared
| Approach | Minimum PHP version | Immutability scope | Best suited for |
|---|---|---|---|
readonly class | 8.2 | All declared properties | DTOs and value objects where every field is fixed |
readonly property | 8.1 | Individual typed properties | Objects that need both fixed and changeable fields |
final class with private setters | 7.4 | Convention only; not enforced by the engine | Legacy runtimes without readonly support |
Constructor promotion plus readonly property | 8.0 | Individual properties | Concise DTOs on PHP 8.0 or 8.1 |
Trade-offs
readonly class removes per-property boilerplate, but it is all-or-nothing: you cannot opt out a single property inside a readonly class. That blocks patterns such as hydration or lazy loading that require writing to properties after construction.
Individual readonly properties allow hybrid objects, but they require discipline. A developer must remember to mark each field, and it is easy to miss one during refactoring.
Both approaches restrict only top-level assignment. If a readonly property holds an array or an object, the elements inside that array or the properties inside that object remain mutable. Serialization with json_encode or serialize works normally for both.
When to choose which option
Choose readonly class when the DTO represents a snapshot, such as an API response payload or a command object handed to a service. The all-or-nothing restriction matches the mental model that the data should not change after it leaves the boundary where it was created.
Choose individual readonly properties when the object is an entity or form model that must remain partially editable. For example, a user profile might have an immutable createdAt timestamp but a mutable displayName field.
Implementation: readonly class DTO
Constructor promotion (available since PHP 8.0) lets you declare and initialize properties directly in the constructor signature. Combined with readonly class on PHP 8.2+, this produces a compact immutable DTO.
<?php
declare(strict_types=1);
readonly class UserDto
{
public function __construct(
public string $email,
public \DateTimeImmutable $createdAt,
public array $roles = [],
) {}
}
The readonly class keyword makes $email, $createdAt, and $roles implicitly readonly. Attempting to assign to any of them after construction triggers an Error.
Runtime validation
Run this snippet in a PHP CLI environment to confirm enforcement. It does not show actual output because results depend on your installed version.
<?php
require __DIR__ . '/vendor/autoload.php';
use App\Dto\UserDto;
$dto = new UserDto(
email: '[contact removed]',
createdAt: new \DateTimeImmutable(),
);
try {
$dto->email = '[contact removed]';
echo 'Property was reassigned.';
} catch (\Error $e) {
echo 'Reassignment blocked: ' . $e->getMessage();
}
$reflection = new \ReflectionClass(UserDto::class);
echo 'Class is readonly: ' . var_export($reflection->isReadOnly(), true) . PHP_EOL;
$property = new \ReflectionProperty(UserDto::class, 'email');
echo 'Property is readonly: ' . var_export($property->isReadOnly(), true) . PHP_EOL;
If the catch block runs, the engine is enforcing immutability at runtime. The Reflection calls return boolean metadata about the class and property declarations.
Limitations and how to check
- Nested mutability:
$dto->roles[] = 'admin'still succeeds because the property holds an array reference; only replacing the$rolesproperty itself is blocked. Check by attempting both reassignment and in-place mutation. - Cannot unset:
unset($dto->email)throws anError. - No partial opt-out: inside a
readonly class, every property is readonly. You cannot mark one property as writable while keeping the rest fixed. - Version requirement: confirm your runtime before deploying readonly classes.
Version check command
Run the following in a terminal. It requires no special permissions and only reads the installed PHP version.
php -v
Expected check: the first line should report PHP 8.2 or higher for readonly class, or PHP 8.1 or higher for individual readonly properties. If the version is lower, use the final class with private setters pattern instead.
Practical result check
After deploying a readonly DTO, verify behavior in your test suite by attempting to mutate each property in a test case and asserting that an Error is thrown. Also assert that ReflectionClass::isReadOnly() returns true for classes intended to be fully immutable. If your test suite uses data providers, include both valid construction and invalid mutation cases. A mutation test that expects Error confirms the engine, not just your coding convention, is enforcing the rule.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.