4

I've noticed strange situation while creating class contructor (__construct).

Here is my code:

public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
        \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
        array $data = []
    )

And:

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
        \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    )

In first case it returns Internal Server Error 500, but in second case all works fine.

Why does agruments order affects?

Thanks in advance!

2
  • May be you extend specific class?
    – Vladyslav
    Commented Sep 14, 2017 at 21:35
  • @Vladyslav I extend AbstractModel class Commented Sep 15, 2017 at 9:44

1 Answer 1

4

Optional parameters MUST be going after the required.

If you omit this rule your code will depend on concrete implementation, because you need to know all default values for optional parameters that can be different in other implementations. This breaks Liskov substitution principle.

It's why the first example does not work.

1
  • Do you know why $data comes last instead of in the order of the parent?
    – linden2015
    Commented Sep 21, 2017 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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