From e416da6aab8c027c0046a2d628e892c982a195de Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Thu, 13 Apr 2023 23:50:06 +0100 Subject: [PATCH] daily-email: add 2023-04-13 --- src/content/daily-email/2023-04-13.md | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/content/daily-email/2023-04-13.md diff --git a/src/content/daily-email/2023-04-13.md b/src/content/daily-email/2023-04-13.md new file mode 100644 index 00000000..f4e01db6 --- /dev/null +++ b/src/content/daily-email/2023-04-13.md @@ -0,0 +1,35 @@ +--- +title: > + Immutable read-only properties in PHP 8.1 +pubDate: 2023-04-13 +permalink: > + archive/2023/04/13/immutable-read-only-properties-in-php-8-1 +tags: + - php +--- + +Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only: + +```php +class AccountDetails { + + public function __construct( + public readonly string $accountNumber, + public readonly string $sortCode, + ) {} + +} +``` + +This means the public properties can be read and used without the need for getter methods, but cannot be overridden - making the DTO immutable. + +Without `readonly`, a DTO can be created and the property values can be changed: + +```php +$accountDetails = new AccountDetails('12345678', '00-00-00'); +$accountDetails->accountNumber = 'banana'; +``` + +With `readonly` set, you'd get a fatal error instead: + +> Fatal error: Uncaught Error: Cannot modify readonly property AccountDetails::$accountNumber in /home/opdavies/tmp/example.php:13