What are the potential pitfalls of using global variables or the $GLOBALS array for database connections in PHP?

Using global variables or the $GLOBALS array for database connections in PHP can lead to potential security vulnerabilities and make the code harder to maintain and debug. It is recommended to use dependency injection or a dedicated class to manage database connections to ensure better encapsulation and reusability of the code.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

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

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