uuid: - value: 9d0e577d-eca2-4b05-9266-00f94901ae69 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: | Refactoring with readonly classes in PHP 8.2 created: - value: '2023-04-16T00: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/16/refactoring-with-readonly-classes-in-php-8-2 langcode: en body: - value: |

Marian Kostadinov (stochnagara on Twitter) 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:

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:

readonly class AccountDetails {

        public function __construct(
          public string $accountNumber,
          public string $sortCode,
        ) {}

      }
      

Thanks for the suggestion, Marian!

format: full_html processed: |

Marian Kostadinov (stochnagara on Twitter) 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:

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:

readonly class AccountDetails {

        public function __construct(
          public string $accountNumber,
          public string $sortCode,
        ) {}

      }
      

Thanks for the suggestion, Marian!

summary: null field_daily_email_cta: { }