Intermediate LevelPHP 8+
How do readonly properties (PHP 8.1) and readonly classes (PHP 8.2) enforce immutability in DTOs?
❓ Interview Prompt: Explain PHP 8.1 readonly properties, PHP 8.2 readonly classes, constructor initialization, and Error exceptions on mutation.
Creating immutable Data Transfer Objects (DTOs) and Value Objects prevents unintended state mutations across domain services.
Immutability Evolution:
•
PHP 8.1 'readonly' Properties: A 'readonly' property can be written to exactly once (typically during constructor initialization). Reassigning the property afterwards throws a fatal 'Error' exception.
•
PHP 8.2 'readonly' Classes: Marking a class as 'readonly' automatically marks every property in the class as readonly and prevents adding dynamic properties!
Code Implementation Example
php
<?php
declare(strict_types=1);
// PHP 8.2+ Readonly Class (All properties implicitly readonly!)
readonly class UserProfileDTO {
public function __construct(
public string $name,
public string $email,
public int $age
) {}
}
$dto = new UserProfileDTO('Alice', 'alice@co.com', 28);
// Fatal Error: Cannot modify readonly property UserProfileDTO::$name
// $dto->name = 'Bob';💡Enforcing strict object immutability using PHP 8.2 readonly classes.
🎯 Interview Key Takeaway
Readonly properties (PHP 8.1) and readonly classes (PHP 8.2) enforce immutability by blocking property mutations after initialization.
#readonly#Immutability#PHP 8.2#DTO#Intermediate
Back to all PHP 8+ Questions→