Constructor property promotion

Since every version of Magento 2.4.4 and onwards supports PHP 8, we can take advantage of PHP 8’s constructor property promotion feature. This feature allows us to greatly simplify our code.

This common pattern of defining a property outside of the constructor, and then assigning a value to it within the constructor body is efficiently handled by constructor property promotion.

Now, we merely define the property's visibility directly within the constructor arguments:

<?php

declare(strict_types=1);

namespace Macademy\\Jumpstart\\Model;

class Product
{
    function __construct(private Category $category) {}

    function getCategoryName()
    {
        return $this->category->getName();
    }
}

This approach performs the same function as before, but with less code.

It's generally best practice to add line breaks to all the constructor arguments. This ensures the code is easy to read, since there are usually many dependencies created like this. And in PHP 8, we can also include a trailing comma, which can cut down on version control diffs in code reviews:

<?php

declare(strict_types=1);

namespace Macademy\\Jumpstart\\Model;

class Product
{
    function __construct(
        private Category $category,
    ) {}

    function getCategoryName()
    {
        return $this->category->getName();
    }
}

I consistently use constructor property promotion when writing any new Magento code. I recommend using it as well, due to the many benefits it provides.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock