2024-01-03 20:00:00 +00:00
---
title: >
2024-09-08 22:09:54 +00:00
Refactoring with readonly classes in PHP 8.2
2024-01-03 20:00:00 +00:00
pubDate: 2023-04-16
permalink: >-
2024-12-19 20:26:33 +00:00
daily/2023/04/16/refactoring-with-readonly-classes-in-php-8-2
2024-01-03 20:00:00 +00:00
tags:
2024-09-08 22:09:54 +00:00
- php
2024-01-03 20:00:00 +00:00
---
Marian Kostadinov ([stochnagara on Twitter](https://twitter.com/stochnagara)) replied to Friday's email about DTOs and value objects to tell me about `readonly` classes, which can be done in PHP 8.2.
Looking at the previous class:
2024-02-18 01:35:59 +00:00
```language-php
2024-01-03 20:00:00 +00:00
class AccountDetails {
public function __construct(
public readonly string $accountNumber,
public readonly string $sortCode,
) {}
}
```
Instead of setting each property as `readonly` , the whole class can instead be marked as `readonly` :
2024-02-18 01:35:59 +00:00
```language-php
2024-01-03 20:00:00 +00:00
readonly class AccountDetails {
public function __construct(
public string $accountNumber,
public string $sortCode,
) {}
}
```
Thanks for the suggestion, Marian!