Magento2: Difference between Type and Virtual Type
--
- Virtual Types are the classes that are instantiated by the ObjectManager but have no physical / concrete class located in /app/code or in /generated.
- Type adjusts existing classes, whereas Virtual Types creates a new class.
- Type affect all the instances, whereas Virtual Type is equivalent of a sub class, where only the sub class has the altered argument values.
- Virtual Type must extend a concrete class type.
- To adjust the constructor parameters for an existing class, use the type declaration. These changes take effect for all class instantiations for that object in that area.
- To create an entirely new type of object that can be injected elsewhere use the virtual type declaration. You need to then inject or utilize this class in XML configuration (in di.xml or as a block).
- Virtual types are useful if the only necessary modifications to a class are the classes that are injected.
- You can’t reference the specific virtual type in a class’ constructor. Rather, your constructor should utilize the concrete class type the virtual type extends.
- You can’t write a class that inherits a virtual type.
You can read more on Type Configuration at https://devdocs.magento.com/guides/v2.4/extension-dev-guide/build/di-xml-file.html#type-configuration
You can read more on Virtual Types at https://devdocs.magento.com/guides/v2.4/extension-dev-guide/build/di-xml-file.html#virtual-types
I have collected these points from various sources on the internet while I was in initial stages of learning Magento2.
I hope these points will be helpful.