PHP 8 interview question · Most asked

What is dependency injection and how does a DI container help?

Summary

Dependency injection means a class receives its collaborators from outside (usually via the constructor) instead of creating them. A container (PSR-11) builds and wires those object graphs automatically.

Longer Answer

DI makes classes testable (inject fakes) and decoupled. A container such as Symfony DI, Laravel's container or PHP-DI uses reflection/autowiring to resolve constructor type hints, manages lifetimes (shared vs new instance), and binds interfaces to implementations.

Avoid the service locator anti-pattern (pulling $container->get() inside business classes): it hides dependencies.

Key Points

  • Constructor injection is preferred
  • Container autowires via reflection
  • PSR-11 standardizes get()/has()
  • Service locator usage hides dependencies

Explanation

Common mistakes

  • Injecting the container itself into services

More most-asked PHP 8 questions

← All PHP 8 questions