1

I am trying to replace an argument via configuration file (di.xml)that's been injected in constructor but it throws an error. Any help will be appreciated

Fatal error: Uncaught TypeError: Argument 1 passed to Mage2\VirtualTypes\Model\Device::__construct() must be an instance of Mage2\VirtualTypes\Model\Apple, instance of Mage2\VirtualTypes\Model\Android given, called in /var/www/html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in /var/www/html/app/code/Mage2/VirtualTypes/Model/Device.php:15 Stack trace:

I removed var/generation, var/di and var/cache folders but it doesn't help. Here is my code sample


class Device implements DeviceInterface
{
 /**
 * @var Apple
 */
 protected $apple;
 /**
 * Device constructor.
 * @param Apple $apple
 */
 public function __construct(Apple $apple)
 {
 $this->apple = $apple;
 }
}

di.xml file

<type name="Mage2\VirtualTypes\Model\Device"> <arguments> <argument name="apple" xsi:type="object">Mage2\VirtualTypes\Model\Android</argument> </arguments> </type>

And Android class looks like


class Android
{
 /**
 * @var AndroidList
 */
 protected $androidList;
 /**
 * Android constructor.
 * @param AndroidList $androidList
 */
 public function __construct(AndroidList $androidList)
 {
 $this->androidList = $androidList;
 }
}
asked Oct 8, 2017 at 7:58
2
  • Your Android class must be inherite from Apple class. Commented Oct 8, 2017 at 8:17
  • Ah thank you @SohelRana. I forgot to extend it from Apple class Commented Oct 8, 2017 at 9:58

1 Answer 1

1

I forgot to extend the Android class from Apple and below is the correct sample code


class Device implements DeviceInterface
{
 /**
 * @var Apple
 */
 protected $apple;
 /**
 * Device constructor.
 * @param Apple $apple
 */
 public function __construct(Apple $apple)
 {
 $this->apple = $apple;
 }
}

di.xml file

<type name="Mage2\VirtualTypes\Model\Device"> <arguments> <argument name="apple" xsi:type="object">Mage2\VirtualTypes\Model\Android</argument> </arguments> </type>

Android class


class Android extends Apple
{
 /**
 * @var AndroidList
 */
 protected $androidList;
 /**
 * Android constructor.
 * @param AndroidList $androidList
 */
 public function __construct(AndroidList $androidList)
 {
 $this->androidList = $androidList;
 }
}
answered Oct 8, 2017 at 10:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.