What are the potential pitfalls of not using Dependency Injection when defining database connections in PHP classes?

Not using Dependency Injection when defining database connections in PHP classes can lead to tightly coupled code, making it difficult to test and maintain. By using Dependency Injection, we can easily swap out different database connections for testing or changing databases without modifying the class itself.

class DatabaseConnection {
    private $db;

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

    public function query($sql) {
        return $this->db->query($sql);
    }
}

// Usage
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$connection = new DatabaseConnection($db);
$result = $connection->query('SELECT * FROM users');