What are the advantages and disadvantages of using global variables in PHP scripts, especially when dealing with database connections?

When dealing with database connections in PHP scripts, using global variables can make the code cleaner and easier to manage. However, relying on global variables can also lead to potential issues such as variable scope conflicts and security vulnerabilities if not handled properly.

// Using a class to manage database connections and avoid global variables
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;
    }
}

// Example of how to use the Database class
$db = new Database("localhost", "username", "password", "database_name");
$connection = $db->getConnection();

// Now you can use $connection to perform database operations