What are the potential pitfalls of using global variables for database connections in PHP?

Using global variables for database connections in PHP can lead to issues such as difficulty in tracking where the connection is being used, potential security vulnerabilities if the global variable is accidentally overwritten or manipulated, and decreased code readability and maintainability. To solve this issue, it's recommended to use a more structured approach such as dependency injection or a singleton pattern to manage database connections.

class Database {
    private static $instance;

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

// To use the database connection
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users");
$stmt->execute();