Magento 2.4.6 – Dynamic Properties are deprecated

Steam replace machine for Dynamic Properties are deprecated error

The problem

Dependency Injection (DI) is a core design pattern used extensively in Magento to manage class dependencies. In Magento, DI is implemented primarily through constructor injection, where dependencies are provided directly to class constructors rather than being instantiated within the class itself.

There would be a lot of interesting things to say about this topic, for example my favorite one is the fact that the configuration of dependencies is declared in XML files, allowing developers to customize and override objects without altering core class code.

This article is not about one cool DI is, but how painful can be when migrating to Magento 2.4.6. In fact since this version uses php 8.2, when we upgrade to it we have to deal with new deprecations of php.

A major update is the deprecation of dynamic property creation. I’m almost sure that any developer, for the sake of rapid development, have previously used dependency injection in constructors without explicitly declaring the instantiated properties within the class, for example like this:

<?php
namespace Vendor\Module\Cron;

class MyCron {
    /**
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\App\ResourceConnection $resource
     */
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->storeManager = $storeManager;
        $this->resource = $resource;
    }

    // ... logics
}

In Magento 2.4.6 this will give the following compilation error:

PHP Deprecated: Creation of dynamic property is deprecated

And you’ll need to explicitly declare the class properties:

/** @var \Magento\Store\Model\StoreManagerInterface */
protected $storeManager;

/** @var \Magento\Framework\App\ResourceConnection */
protected $resource;

The solution

Ok, the solution is simply, but what if you have to upgrade a project with hundreds of classes with this problem?

I wrote this script:

fix_dynamic_properties.php

that can quickly sanitize the code of a module. I simply launch it with the syntax:

fix_dynamic_properties.php <verbose> <solve> <directory> <only_this>

Then from the git section of VS Code I check the modification. It assumes that the property has the same name of the constructor parameter, since this is my convention. I find some mismanagement in property named with the underscore that are declared as mixed (it still should be a working code).

Here the git with the script and documentation: https://github.com/zagonico86/magento2-fix-dynamic-properties/

There you can find other small Magento utility modules like how to modify a profiler.