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
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.