Constructor property promotion – Code Refactoring School

Code refactoring school is a series of short articles where we cover some of the most common tactics to improve code quality and readability. In this article, we will be discussing constructor property promotion which was introduced in PHP 8.0. See the rfc for more details.

The problem

When creating new class with value objects, before PHP 8.0, we were forced to write something like

class Company {
	
    public string $name;
    public int $size;
 
    public function __construct(
        string $name,
        int $size = 1
    ) {
        $this->name = $name;
        $this->size = $size;
    }
}

What is the problem with this code? There’s a lot of boilerplate code you must always write. Let’s take value object $name into consideration. First, you need to define class property with public string $name. Then, you must define constructor argument string $name, which people mostly named the same as the property name. Finally, you must assign value you received in $name argument to class property with $this->name = $name.

Seeing this as very common thing which constantly repeats all over the codebases, PHP maintainers righteously voted in favour of implementation of constructor property promotion with 46 for and 10 against votes.

The solution

With constructor property promotion, we can simplify our code to

class Company {
	
    public function __construct(
        public string $name,
        public int $size = 0
    ) {}
}

Under the hood, PHP converts this code to the original code and then continues processing to maintain full backward compatibility.

Worth mentioning

Finally, there’s few things worth mentioning which you should be aware of. Since they are awesomely covered in depth in this stitcher.io post, we will just mention them here.

  1. You can mix traditional syntax and constructor property promotion, but it is not advisable since it reduces code readability – use either one or the other in same class
  2. No duplicates – class property and promoted property can’t have the same name due to the fact that the code is converted from promoted to normal class property before execution
  3. Promoted properties must always be typed
  4. Default values must be “simple” – in other words, you can only assign “simple” values like strings or numerics, while creating new object of class is not allowed
  5. You can add Doc comments and Attributes on promoted properties
  6. Variadic parameters cannot be promoted
  7. Promoted properties are allowed in Traits too

If you want to level up your apps and your codebase, check out other posts on our blog xdoo.hr.

Do you need help with updating your old php codebase with latest constructor promoted properties optimizations?

For anything related to PHP or Laravel development send us your inquiry to [email protected]!


Leave a Reply

Your email address will not be published. Required fields are marked *