What are the potential pitfalls of using a singleton pattern in PHP for database connections?

One potential pitfall of using a singleton pattern for database connections in PHP is that it can lead to tightly coupled code, making it difficult to switch to a different database system in the future. To solve this issue, you can implement dependency injection to decouple the database connection from the rest of your code, allowing for easier testing and maintenance.

class Database {
    private static $instance;

    private function __construct() {
        // Private constructor to prevent instantiation
    }

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
        }
        return self::$instance;
    }
}

class UserRepository {
    private $db;

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

    public function getUsers() {
        $stmt = $this->db->query('SELECT * FROM users');
        return $stmt->fetchAll();
    }
}

// Usage
$db = Database::getInstance();
$userRepository = new UserRepository($db);
$users = $userRepository->getUsers();