oliverdavies.uk/source/_daily_emails/2023-04-13.md

36 lines
1 KiB
Markdown
Raw Normal View History

2024-01-03 20:00:00 +00:00
---
title: >
2024-02-07 20:01:19 +00:00
Immutable read-only properties in PHP 8.1
2024-01-03 20:00:00 +00:00
pubDate: 2023-04-13
permalink: >-
2024-02-07 20:01:19 +00:00
archive/2023/04/13/immutable-read-only-properties-in-php-8-1
2024-01-03 20:00:00 +00:00
tags:
2024-02-07 20:01:19 +00:00
- php
2024-01-03 20:00:00 +00:00
---
Continuing with yesterday's data transfer object (DTO) example, something that can be done since PHP 8.1 is to make properties read-only:
```language-php
2024-01-03 20:00:00 +00:00
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:
```language-php
2024-01-03 20:00:00 +00:00
$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