Cleaner PHP code with promoted constructor properties

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:

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:

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.

- Oliver

P.S. Do you need immediate access to an expert Drupal Developer? With my Drupal development subscription, make unlimited requests for a fixed monthly price in less time than posting to a job board!

Was this useful?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.