What is dependency injection in PHP?
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.
Previous
What is the difference between array_map, array_filter, and array_reduce?
Next
What is the Iterator interface in PHP?