$GLOBALS

(PHP 4, PHP 5, PHP 7, PHP 8)

$GLOBALSReferencia todas variáveis disponíveis no escopo global

Descrição

Um array associativo contendo referências para todas as variáveis que estão atualmente definidas no escopo global do script. O nome das variáveis são chaves do array.

Exemplos

Exemplo #1 Exemplo da $GLOBALS

<?php

function teste()
{
$foo = "variável local";

echo
'$foo no escopo global: ' . $GLOBALS["foo"] . "\n";
echo
'$foo no escopo atual: ' . $foo . "\n";
}

$foo = "Conteúdo de exemplo";
teste();

?>

O exemplo acima produzirá algo semelhante a:

$foo no escopo global: Conteúdo de exemplo
$foo no escopo atual: variável local

Aviso

A partir do 8.1.0, acesso de escrita a todo o array $GLOBALS não é mais suportado:

Exemplo #2 Escrever em todo o $GLOBALS irá resultar em um erro.

<?php

// Gera um erro em tempo de compilação:
$GLOBALS = [];
$GLOBALS += [];
$GLOBALS =& $x;
$x =& $GLOBALS;
unset(
$GLOBALS);
array_pop($GLOBALS);
// ...e qualquer outra operação de escrita/leitura em $GLOBALS

?>

Notas

Nota:

Esta é uma variável 'superglobal' ou variável global automática. Isso significa simplesmente que ela está disponível em todos os escopos de um script. Não há necessidade de usar global $variable; para acessá-la dentro de funções ou métodos.

Nota: Disponibilidade da variável

Diferente de todas as outras superglobais, $GLOBALS tem essencialmente sempre estado disponível no PHP.

Nota:

A partir do PHP 8.1.0, $GLOBALS agora é uma cópia somente-leitura da tabela de símbolos globais. Isto é, variáveis globais não podem ser modificadas por meio de suas cópias. Anteriormente, o array $GLOBALS era excluído do comportamento usual "por valor" dos arrays PHP e variáveis globais podiam ser modificadas por meio de suas cópias.

<?php

// Antes do PHP 8.1.0
$a = 1;

$globals = $GLOBALS; // Cópia ostensiva "por valor"
$globals['a'] = 2;
var_dump($a); // int(2)

// A partir do PHP 8.1.0,
// isto não mais modifica $a. O comportamento anterior violava a semântica "por valor".
$globals = $GLOBALS;
$globals['a'] = 1;

// Para restaurar o comportamento anterior, itera sua cópia e atribui cada propriedade de volta ao $GLOBALS.
foreach ($globals as $key => $value) {
$GLOBALS[$key] = $value;
}

?>

adicione uma nota

Notas Enviadas por Usuários (em inglês) 4 notes

up
20
inafeeur at gmail dot com
2 years ago
We can be more clear with the extension of the given example.Before PHP Version 8.1<?php  $a = 1;  $globals = $GLOBALS;  $globals['a'] = 2;  echo $a; // 2  echo $globals['a']; // 2  echo $GLOBALS['a'];  // 2?>After PHP Version 8.1<?php  $a = 1;  $globals = $GLOBALS;  $globals['a'] = 2;  echo $a; // 1  echo $globals['a']; // 2  echo $GLOBALS['a'];  // 1?>
up
17
therandshow at gmail dot com
14 years ago
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is I'm not sure, but I've never liked $GLOBALS much anyways.
up
16
mstraczkowski at gmail dot com
12 years ago
Watch out when you are trying to set $GLOBALS to the local variable.Even without reference operator "&" your variable seems to be referenced to the $GLOBALSYou can test this behaviour using below code<?php/** * Result: * POST: B, Variable: C * GLOBALS: C, Variable: C */ // Testing $_POST$_POST['A'] = 'B'; $nonReferencedPostVar = $_POST;$nonReferencedPostVar['A'] = 'C'; echo 'POST: '.$_POST['A'].', Variable: '.$nonReferencedPostVar['A']."\n\n"; // Testing Globals$GLOBALS['A'] = 'B'; $nonReferencedGlobalsVar = $GLOBALS;$nonReferencedGlobalsVar['A'] = 'C'; echo 'GLOBALS: '.$GLOBALS['A'].', Variable: '.$nonReferencedGlobalsVar['A']."\n\n";
up
13
vittorio.zamparella at famous googlemail
8 years ago
I finally found information about superglobals not being found in $GLOBALS:https://bugs.php.net/bug.php?id=65223&edit=2------------------------------------- [2013-07-09 12:00 UTC] johannes @php.net[...]super-globals (aka. auto globals) are not added to symbol tables by default for performance reasons unless the parser sees need. i.e. <?php$_SERVER;print_r($GLOBALS);?>will list it. You can also control this using auto_gloals_jit in php.ini: http://www.php.net/manual/en/ini.core.php#ini.auto-globals-jit-------------------------------------http://www.php.net/manual/en/language.variables.variable.php-------------------------------------WarningPlease note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.-------------------------------------
To Top