What are the benefits of using dependency injection to avoid global variables and improve code modularity in PHP applications?
Using dependency injection in PHP applications helps avoid global variables by allowing dependencies to be passed into a class or function rather than relying on global state. This improves code modularity as each class or function is responsible for its own dependencies, making it easier to test and maintain. Additionally, dependency injection promotes loose coupling between components, making it easier to swap out dependencies or make changes without affecting other parts of the code.
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
public function query($sql) {
return $this->connection->query($sql);
}
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$result = $database->query('SELECT * FROM users');