In Magento 2, What is the main difference between adding an object in Constructor and adding via object Manager?

Adding an object in Constructor:

public function __construct(
    Magento\Indexer\Model\Processor $processor
    $this->_processor = $processor;

Adding via Object Manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

The main difference is when adding an object in Constructor,the object is instantiates at the beginning of the bootstrapping process by the Object Manager itself. Whereas Adding via Object Manager the object is instantiates only on request.

The better process is adding an object in Constructor because the object instantiation is completely handled by Framework, you no need to do anything after that and it can be used throughout the class. for more please read this.

|improve this answer|||||
  • Instead of loading the object in the constructor, Can I just call the object using object manager whenever it's needed? – Octopus May 29 '18 at 9:10
  • it will works but better way to inject the dependent class in the constructor. – Prasanta Hatui May 29 '18 at 9:16
  • 1
    why is it better? Can you please explain it briefly? – Octopus May 29 '18 at 9:18
  • I have updated the answer. Please check. – Prasanta Hatui May 29 '18 at 9:31

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.