Constructor Property Promotion

๐Ÿ›’ B-Online Store

Premium Magento 2 Extensions & Services

Enhance your e-commerce store with high-quality extensions and expert Magento development services. Trusted by thousands of merchants worldwide!

๐Ÿ’ฌ WhatsApp Button โšก Flash Sale ๐Ÿท๏ธ Product Labels ๐ŸŒ Translation Suite
๐Ÿ”ฅ UP TO 71% OFF Limited Time!
โญ Thousands of Merchants ๐Ÿ›ก๏ธ Quality Guaranteed โšก Instant Download
YouTube player

With the advent of Magento 2.4.4 and subsequent versions embracing PHP 8, we’re poised to leverage the innovative constructor property promotion feature introduced in PHP 8. This powerful feature streamlines our coding efforts significantly.

Traditionally, the practice involved declaring a class property separately and then initializing it within the constructor. Constructor property promotion elegantly condenses this two-step process.

<?php

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

class Product {

    /**
     * @param Category $category
     */
    public function __construct(private Category $category,){}

    /**
     * @return string
     */
    function getCategoryName(): string
    {
        return $this->category->getName();
    }
}

By simply specifying the property’s visibility within the constructor’s parameters, we achieve the same outcome more succinctly:

This refined approach retains the original functionality while minimizing the code footprint.

For enhanced readability, especially when dealing with numerous dependencies, it’s advisable to format constructor arguments with line breaks. PHP 8 further enhances this by allowing a trailing comma in the argument list, reducing the potential for version control conflicts.

Embracing constructor property promotion in new Magento development projects is something I advocate strongly for. The efficiency and clarity it brings to the code are invaluable.