{ "uuid": [ { "value": "d421a5a4-8025-4809-8a30-68c723e46af6" } ], "langcode": [ { "value": "en" } ], "type": [ { "target_id": "daily_email", "target_type": "node_type", "target_uuid": "8bde1f2f-eef9-4f2d-ae9c-96921f8193d7" } ], "revision_timestamp": [ { "value": "2025-05-11T09:00:44+00:00" } ], "revision_uid": [ { "target_type": "user", "target_uuid": "b8966985-d4b2-42a7-a319-2e94ccfbb849" } ], "revision_log": [], "status": [ { "value": true } ], "uid": [ { "target_type": "user", "target_uuid": "b8966985-d4b2-42a7-a319-2e94ccfbb849" } ], "title": [ { "value": "Immutable read-only properties in PHP 8.1\n" } ], "created": [ { "value": "2023-04-13T00:00:00+00:00" } ], "changed": [ { "value": "2025-05-11T09:00:44+00:00" } ], "promote": [ { "value": false } ], "sticky": [ { "value": false } ], "default_langcode": [ { "value": true } ], "revision_translation_affected": [ { "value": true } ], "path": [ { "alias": "\/daily\/2023\/04\/13\/immutable-read-only-properties-in-php-8-1", "langcode": "en" } ], "body": [ { "value": "\n
Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:<\/p>\n\n
class AccountDetails {\n\n public function __construct(\n public readonly string $accountNumber,\n public readonly string $sortCode,\n ) {}\n\n}\n<\/code><\/pre>\n\nThis means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable.<\/p>\n\n
Without readonly<\/code>, a DTO can be created and the property values can be changed:<\/p>\n\n$accountDetails = new AccountDetails('12345678', '00-00-00');\n$accountDetails->accountNumber = 'banana';\n<\/code><\/pre>\n\nWith readonly<\/code> set, you'd get a fatal error instead:<\/p>\n\n\n Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in \/home\/opdavies\/tmp\/example.php:13<\/p>\n<\/blockquote>\n\n ",
"format": "full_html",
"processed": "\n
Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:<\/p>\n\n
class AccountDetails {\n\n public function __construct(\n public readonly string $accountNumber,\n public readonly string $sortCode,\n ) {}\n\n}\n<\/code><\/pre>\n\nThis means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable.<\/p>\n\n
Without readonly<\/code>, a DTO can be created and the property values can be changed:<\/p>\n\n$accountDetails = new AccountDetails('12345678', '00-00-00');\n$accountDetails->accountNumber = 'banana';\n<\/code><\/pre>\n\nWith readonly<\/code> set, you'd get a fatal error instead:<\/p>\n\n\n Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in \/home\/opdavies\/tmp\/example.php:13<\/p>\n<\/blockquote>\n\n ",
"summary": null
}
]
}