Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

$GLOBALS

The superglobal $GLOBALS exposes global variables under their string names from any scope.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

$GLOBALS["count"] += 1;

The superglobal $GLOBALS exposes global variables under their string names from any scope. Writing a named element changes the corresponding global even when the function has a different local variable with that name. In PHP 8.1 and later replacing or referencing the entire $GLOBALS array is forbidden, while individual element updates remain available. Copying it and changing a scalar entry in the copy need not change that global.

$count = 2;
function update(): array {
    $count = 50;
    $GLOBALS["count"] += 3;
    $snapshot = $GLOBALS;
    $snapshot["count"] = 90;
    return [$count, $snapshot["count"]];
}
echo json_encode([update(), $count]);
[[50,90],5]

Examples

<?php
$count = 2;
function update(): array {
    $count = 50;
    $GLOBALS["count"] += 3;
    $snapshot = $GLOBALS;
    $snapshot["count"] = 90;
    return [$count, $snapshot["count"]];
}
echo json_encode([update(), $count]);

Result

[[50,90],5]

Sources