What is the potential risk of using global variables in PHP for database connections?

Using global variables for database connections in PHP can pose a security risk as they are accessible from anywhere in the code, making it easier for malicious users to manipulate the connection settings. To mitigate this risk, it is recommended to encapsulate the database connection in a class and use dependency injection to pass the connection object where it is needed.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

    public function getConnection() {
        return $this->connection;
    }
}

// Usage
$db = new Database('localhost', 'username', 'password', 'database');
$connection = $db->getConnection();