How does Dependency Injection play a role in avoiding static dependencies like Singletons in PHP?

Static dependencies like Singletons can lead to tightly coupled code and make unit testing difficult. Dependency Injection helps avoid this by allowing dependencies to be passed into a class from the outside, making the code more flexible and easier to test.

// Bad example using a Singleton
class Database {
    private static $instance;

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

// Good example using Dependency Injection
class Database {
    private $connection;

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

// Usage of Dependency Injection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);