1

In my understanding, argument passed to a function/method are strictly mapped to your function call, and the arguments must be arranged in correct order to map what you pass in your function call.

e.g. function test(a,b){
     return ....
}
$result = test(myValue1, myValue2);

But in magento2, when we override a class, we can inject more & more argument as we like , e.g.

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magestore\Bannerslider\Model\ResourceModel\Banner\CollectionFactory $bannerCollectionFactory,
        array $data = []
    ) {

After override, one more argument is injected:

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magestore\Bannerslider\Model\ResourceModel\Banner\CollectionFactory $bannerCollectionFactory,
        \Magestore\Bannerslider\Model\SliderFactory $sliderFactory,
        SliderModel $slider,
        array $data = []
    ) {

Why php could accept this changes? Couldn't it crash the method call as the number of arguments are not the same?

2

The reason is that Magento instantiates classes dynamically.

From \Magento\Framework\ObjectManager\Factory\AbstractFactory:

protected function createObject($type, $args)
{
    return new $type(...array_values($args));
}

This method instantiates a class where $type is the class to be instantiated and $args is an array of arguments. This allows for flexibility in regards to the arguments passed to any given class constructor.

1

Magento 2 has a system which takes the type hints from the constructor and actually generates the objects which then get injected at runtime.

1

Why PHP could accept this changes?

  • in object oriented programming constructor is not part of an interface
  • it does not make sense to not allow it because inheritance, in this case, doesn't make sense at all

Couldn't it crash the method call as the number of arguments are not the same?

No, is would not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.