vijaykumar
vijaykumar

Reputation: 4806

Dependency injection on abstract constructor

class Test {
  function test()
  {
      return 'test';
  }
}


abstract class MasterAbstract {

    public function __construct (Test $test)
    {
        $this->test = test;
    }

    protected function runMaster()
    {
        return $this->test->test();
    }

}

class Child extends MasterAbstract
{
    public function run()
    {
        return 1212;
    }
}

Case 1:

$c = new Child();
echo $c->run;

Getting error here

Argument 1 passed to MasterAbstract::__construct() must be an instance of Test, none given

Case 2: In this i'm not creating any object for the child or someotherController. It's working . I'm using laravel framework

class SomeotherController 
 {
    private $ch;

    public function __constructor(Child $ch)
    {
       $this->ch = $ch;
    }

    public function run()
    {
       return $this->ch->run();
    }
 }

Please anyone explain how these two case working?

Upvotes: 1

Views: 2159

Answers (1)

Filip Koblański
Filip Koblański

Reputation: 10008

In the case #2 You injects Child object class with constructor's parameter which is resolved by Laravel's IoC

In case #1 You create Child object with new statment and You need to give a Test class in the parameter.

If You want to go like this You cal call the app container make method:

$c = app(Child::class);
echo $c->run;

The app(Child::class) is the same as \App::make(Child::class). It gives You new object's instance and automaticly resolves the dependencies.

Upvotes: 2

Related Questions