Superglobal variables

In addition to global variables, PHP also knows so-called superglobal variables, which are automatically available in every scope even without an explicit global declaration:

<?php declare(strict_types=1);

some_function();

function some_function(): void
{
    var_dump($_GET);
    var_dump($_POST);
}
superglobalVariables.php
superglobalVariables.php:7:
array(0) {
}
superglobalVariables.php:8:
array(0) {
}
Output of superglobalVariables.php
Execute superglobalVariables.php

There are more superglobal variables listed in the PHP manual.

Historically, PHP also has the superglobal associative array $GLOBALS, which we can use to access global variables as an alternative:

<?php declare(strict_types=1);

$a = 'test';
$GLOBALS['a'] = 'test!';
var_dump($a);
writingGlobal.php
writingGlobal.php:5:
string(5) "test!"
Output of writingGlobal.php
Execute writingGlobal.php

Since version PHP 8.1, write access is only possible to individual global variables. Any attempt to write access to the entire $GLOBALS since PHP 8.1 leads directly to a translation error:

<?php declare(strict_types=1);

var_dump($GLOBALS);
$GLOBALS = [];
var_dump($GLOBALS);
writingGlobals-will-fail.php
PHP Fatal error:  $GLOBALS can only be modified using the $GLOBALS[$name] = $value syntax in writingGlobals-will-fail.php on line 4
Output of writingGlobals-will-fail.php
Execute writingGlobals-will-fail.php

We can see that not even the first var_dump() has been executed. The program execution was not even started because the compiler cut us off directly.

If you are already using global variables, then declare them as global and don't use $GLOBALS.

Questions for learning control

  1. Accessing data from an HTTP request is very convenient thanks to superglobal variables. What disadvantages does this have?
  2. "After the update to PHP 8.1, access to global variables is no longer possible." Comment on this statement.
  3. Formulate sensible rules for your coding guidelines on how global variables should or may be used.