Bird
0
0

Which of the following is the correct way to inject a service into a Laravel controller constructor?

easy📝 Syntax Q12 of 15
Laravel - Controllers
Which of the following is the correct way to inject a service into a Laravel controller constructor?
Apublic function __construct($service) { $this->service = new Service(); }
Bpublic function __construct(Service $service) { $this->service = $service; }
Cpublic function __construct() { $this->service = Service::class; }
Dpublic function __construct(Service $service) { $service = new Service(); }
Step-by-Step Solution
Solution:
  1. Step 1: Check constructor parameter type hinting

    public function __construct(Service $service) { $this->service = $service; } correctly type hints the Service class in the constructor parameter.
  2. Step 2: Verify assignment to class property

    public function __construct(Service $service) { $this->service = $service; } assigns the injected service to a class property for later use, which is correct.
  3. Final Answer:

    public function __construct(Service $service) { $this->service = $service; } -> Option B
  4. Quick Check:

    Constructor injection = type hint + assign property [OK]
Quick Trick: Type hint service in constructor and assign to property [OK]
Common Mistakes:
  • Not type hinting the service class in constructor
  • Creating new service instance inside constructor instead of injecting
  • Assigning class name string instead of object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes