2024-01-03 20:00:00 +00:00
|
|
|
---
|
|
|
|
title: >
|
2024-09-08 22:09:54 +00:00
|
|
|
Cleaner PHP code with promoted constructor properties
|
2024-01-03 20:00:00 +00:00
|
|
|
pubDate: 2023-04-12
|
|
|
|
permalink: >-
|
2024-12-19 20:26:33 +00:00
|
|
|
daily/2023/04/12/cleaner-php-code-with-promoted-constructor-properties
|
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
|
|
|
---
|
|
|
|
|
|
|
|
One of my favorite features that was introducted in PHP 8 was promoted constructor properties.
|
|
|
|
|
|
|
|
If I'm passing arguments into a constructor, I can declare a visibility and it will be promoted to a property on the class.
|
|
|
|
|
|
|
|
Here's an example of a value of a data transfer object that accepts a sort code and account number as strings:
|
|
|
|
|
2024-02-18 01:35:59 +00:00
|
|
|
```language-php
|
2024-01-03 20:00:00 +00:00
|
|
|
class AccountDetails {
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
public string $accountNumber,
|
|
|
|
public string $sortCode,
|
|
|
|
) {}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Without promoted constructor properties, I'd need to create the properties and assign them manually, and I'd have this:
|
|
|
|
|
2024-02-18 01:35:59 +00:00
|
|
|
```language-php
|
2024-01-03 20:00:00 +00:00
|
|
|
class AccountDetails {
|
|
|
|
|
|
|
|
public string $accountNumber;
|
|
|
|
|
|
|
|
public string $sortCode;
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
string $accountNumber,
|
|
|
|
string $sortCode,
|
|
|
|
) {
|
|
|
|
$this->accountNumber = $accountNumber;
|
|
|
|
$this->sortCode = $sortCode;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Whilst text editors and IDEs can create the properties automatically, I prefer this as it's less code, more readable and easier to understand.
|