cancel
Showing results for 
Search instead for 
Did you mean: 

How to pass parameter via dependency injection

How to pass parameter via dependency injection

Hello, I would like to know if there is possible to inject string or number as parameter to class, for example I have some class with constructor:

    public function __construct(
        \Magento\Framework\App\State $state,
        \Magento\Store\Model\App\Emulation $emulation,
        \Magento\Framework\ObjectManagerInterface $objectManager,
int $someIntegerValue ){ $this->state = $state; $this->emulation = $emulation; $this->objectManager = $objectManager; }

I don't know, how can I pass integer value to this. Is it possible? 

Thanks,

Sebastian

2 REPLIES 2

Re: How to pass parameter via dependency injection

Hello @Sebastian222 

 

Yes, in Magento 2, you can inject string or number parameters into a class constructor.

Here's an example of how you can define a class with string and number parameters in its constructor:

public function __construct(
        \Magento\Framework\App\State $state,
        \Magento\Store\Model\App\Emulation $emulation,
        \Magento\Framework\ObjectManagerInterface $objectManager,
       int $someIntegerValue
    ){
        $this->state = $state;
        $this->emulation = $emulation;
        $this->objectManager = $objectManager;
        $this->numberParam = $someIntegerValue;    }

Hope it helps !

If you find our reply helpful, please give us kudos.

 

A Leading Magento Development Agency That Delivers Powerful Results, Innovation, and Secure Digital Transformation.

 

WebDesk Solution Support Team

Get a Free Quote | | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789

 

 

Thank You,


WebDesk Solution Support Team
Get a Free Quote | Email | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789


Location: 150 King St. W. Toronto, ON M5H 1J9

Re: How to pass parameter via dependency injection

@Sebastian222 

Hey,

You can add class arguments by adding dependencies in di.xml file. e.g.,

<type name="Vendor\Extension\Model\Class1">
    <arguments>
        <argument name="arg1" xsi:type="object">Vendor\Extension\Model\Class2</argument>
        <argument name="arg2" xsi:type="string">testArgument</argument>
      ...
    </arguments>
</type>
Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.