What is Dependency Injection and why is it recommended over global variables or constructor-based instantiation in PHP?

Dependency Injection is a design pattern in which the dependencies of a class are provided from the outside rather than created internally. This allows for better flexibility, testability, and maintainability of the code. It is recommended over global variables or constructor-based instantiation in PHP because it promotes loose coupling between classes and makes it easier to swap out dependencies or mock them for testing purposes.

class Database {
    private $connection;

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

    public function query($sql) {
        // execute query using $this->connection
    }
}

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