How can dependency injection be implemented in PHP classes to avoid using global variables?

Global variables can lead to tightly coupled code and make testing and maintaining the code difficult. To avoid using global variables in PHP classes, dependency injection can be implemented. Dependency injection involves passing dependencies (objects or values) into a class through its constructor or setter methods, rather than relying on global variables.

<?php

class Database {
    private $connection;

    public function __construct($connection) {
        $this->connection = $connection;
    }

    public function query($sql) {
        // Use $this->connection to execute the query
    }
}

$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$database->query('SELECT * FROM users');

?>