🐘 PHP Intermediate

What is dependency injection in PHP?

Why Interviewers Ask This

This question targets practical, hands-on experience with PHP. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Dependency Injection (DI) is a design pattern where dependencies (objects a class needs) are provided from outside rather than created internally. Instead of class UserService { public function __construct() { $this->db = new Database(); } }, you inject it: class UserService { public function __construct(private Database $db) {} }. Benefits: loosely coupled code, easily testable (inject mock dependencies in tests), and flexible (swap implementations by injecting different objects). DI Containers (like PHP-DI, Symfony's DI Container, Laravel's IoC Container) automate the wiring of dependencies throughout an application using reflection and configuration. DI is the foundation of modern PHP frameworks.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.