DEV Community

Cover image for Dive into PHP8. Part 1 - Constructor Property Promotion
Krzysztof Szala
Krzysztof Szala

Posted on

Dive into PHP8. Part 1 - Constructor Property Promotion

A new major version of PHP is set for an official release on December 3. Along with numerous bug fixes and small improvements, developers from around the globe will also get some new interesting features. The list isn't closed yet, but, despite that, we may already check what we can expect. I'm going to prepare a series of short articles, and each one will focus on something else. Let's start!

In the first post, I would like to introduce to you Constructor Property Promotion. A concept well known in languages such as Hack, Korlin or TypesScript is going to be introduced in PHP 8. How does it work and in what kind of situations can it be useful? Let's look at the example below:

Alt Text

Simple Value-Object, right? We deal with classes like these almost every day. Isn't it a little annoying that we must write the whole boilerplate code to set those values from constructor to class properties? Constructor Property Promotion feature will solve that problem for us, and enable writing the kind of code presented above more simply and shortly. Check it out:

Alt Text

We can simply add an access modifier before the type declaration of the constructor parameter, and that parameter will be automatically assigned to the class property with the same name. We can say that parameters which have a set access modifier are promoted.

It's possible to mix promoted properties with regular properties declaration. Here is an example:

Alt Text

The example provided above is equivalent to the code below:

Alt Text

Constructor Property Promotion will be available only for regular classes and traits. We won't be able to promote properties in interfaces and abstract classes (although we can declare __constructor() method in them).

If you use a lot of Value Object (VO) or Data Transfer Object (DTO) – Constructor Property Promotion will shorten and simplify your code. A similar feature has been requested for comments several times, but only the implementation written by Nikita Popov got enough positive votes and will be merged into the new PHP version. You can read more about it in this RFC.

In the next part of our "Dive into PHP8" series, we will be talking about the implementation of Union Types. Stay tuned!


This article was originally published on my company's blog. You can check it here.

Top comments (0)