Difference between constructor property promotion in PHP 7’s v/s PHP 8’s / Magento 2

Magento 2.4.4 finally released has a big feature — support for PHP 8! This new version of PHP introduces a feature called Constructor Property Promotion, which can greatly simplify your Magento 2 code.

Naturally, I’m very happy with the constructor property promotion declaration we can see the code difference below of two versions.

So in PHP 7.x

class View
    protected $resultForwardFactory;

    private $request;

    private $pageHelper;

    public function __construct(
        Context $context,
        RequestInterface $request,
        PageHelper $pageHelper,
        ForwardFactory $resultForwardFactory
    ) {
        $this->request = $request;
        $this->pageHelper = $pageHelper;
        $this->resultForwardFactory = $resultForwardFactory;

In PHP 8.x

class View
    public function __construct(
        protected RequestInterface $request, 
        private PageHelper $pageHelper, 
        private ForwardFactory $resultForwardFactory,
    ) {}

In short: property promotion allows you to combine class fields, constructor definition and variable assignments all into one syntax, in the construct parameter list.

If you have any questions or feedback so please feel free to ask in the comments or reach me my email address chelumallap@gmail.com

Thank you so much for reading this blog and keep support me and i will coming with the new blog.

Related Posts

Leave a Reply

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