PHP 8.4.0 RC3 available for testing

Escopo de variáveis

O escopo de uma variável é o contexto onde ela está definida. O PHP tem um escopo de função e um escopo global. Qualquer variável definida fora de uma função está limitada ao escopo global. Quando um arquivo é incluído, o código que ele contém herda o escopo da variável da linha na qual a inclusão ocorre.

Exemplo #1 Exemplo de escopo global de variável

<?php
$a
= 1;
include
'b.inc'; // Variável $a estará disponível dentro de b.inc
?>

Qualquer variável criada dentro de uma função nomeada ou de uma função anônima é limitada ao escopo do corpo da função. Entretanto, funções de seta vinculam variáveis ​​do escopo pai para disponibilizá-las dentro do corpo. Se uma inclusão de arquivo ocorrer dentro de uma função dentro do arquivo chamador, as variáveis ​​contidas no arquivo chamado estarão disponíveis como se tivessem sido definidas dentro da função chamadora.

Exemplo #2 Exemplo de escopo local de variável

<?php
$a
= 1; // escopo global

function test()
{
echo
$a; // Variável $a é indefinida já que refere-se a uma versão local de $a
}
?>

O exemplo acima irá gerar um E_WARNING de variável indefinida (ou um E_NOTICE antes do PHP 8.0.0). Isto acontece porque a instrução echo refere-se a uma versão local da variável $a, e não possui nenhum valor atribuído neste escopo. Pode-se perceber que esta é uma pequena diferença em relação à linguagem C, em que variáveis globais estão automaticamente disponíveis para funções a menos que tenham sido substituídas por uma definição local. Isto pode causar problemas quando uma variável global for inadvertidamente modificada. No PHP, as variáveis globais precisam ser declaradas como globais dentro de uma função, se elas precisarem ser utilizadas na função.

A palavra-chave global

A palavra-chave global é usada para vincular uma variável de um escopo global a um escopo local. A palavra-chave pode ser usada com uma lista de variáveis ​​ou com uma única variável. Uma variável local será criada referenciando a variável global de mesmo nome. Se a variável global não existir, a variável será criada no escopo global e receberá o valor null.

Exemplo #3 Usando global

<?php
$a
= 1;
$b = 2;

function
Soma()
{
global
$a, $b;

$b = $a + $b;
}

Soma();
echo
$b;
?>

O exemplo acima produzirá:

3

Declarar $a e $b como globais na função fará com que todas as referências a essas variáveis refiram-se às versões globais. Não há um limite para o número de variáveis globais que podem ser manipuladas por uma função.

Uma segunda maneira de acessar variáveis do escopo global é utilizando o array especial $GLOBALS definido pelo PHP. O exemplo anterior poderia ser reescrito como:

Exemplo #4 Usando $GLOBALS no lugar de global

<?php
$a
= 1;
$b = 2;

function
Soma()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Soma();
echo
$b;
?>

O array $GLOBALS é um array associativo, com o nome da variável global na chave e o conteúdo dessa variável no valor do elemento do array. Veja que $GLOBALS existe em qualquer escopo, isto porque $GLOBALS é uma superglobal. Eis um exemplo demonstrando o poder das superglobais:

Exemplo #5 Exemplo demonstrando superglobals e escopos

<?php
function test_superglobal()
{
echo
$_POST['name'];
}
?>

Nota: Utilizar a instrução global fora de uma função não é um erro. Pode ser utilizado se o arquivo for incluído de dentro de uma função.

Utilizando variáveis static

Outro recurso importante do escopo de variáveis é a variável estática. Uma variável estática existe somente no escopo local da função, mas não perde seu valor quando a execução do programa deixa o escopo. Considere o seguinte exemplo:

Exemplo #6 Exemplo demonstrando a necessidade de variáveis estáticas

<?php
function Teste()
{
$a = 0;
echo
$a;
$a++;
}
?>

Essa função é inútil, já que cada vez que é chamada, define $a com o valor 0, e exibe 0. A instrução $a++ , que aumenta o valor da variável, não tem sentido já que assim que a função termina, a variável $a desaparece. Para fazer um função de contagem útil, que não perderá a contagem atual, a variável $a será declarada como estática:

Exemplo #7 Exemplo de uso de variáveis estáticas

<?php
function Teste()
{
static
$a = 0;
echo
$a;
$a++;
}
?>

Agora, a variável $a é inicializada apenas na primeira chamada da função e cada vez que a função test() for chamada, exibirá o valor de $a e depois o incrementará.

Variáveis estáticas fornecem uma solução para lidar com funções recursivas. A seguinte função recursiva conta até 10, utilizando a variável estática $count para saber quando parar:

Exemplo #8 Variáveis estáticas em funções recursivas

<?php
function Teste()
{
static
$count = 0;

$count++;
echo
$count;
if (
$count < 10) {
Teste();
}
$count--;
}
?>

Antes do PHP 8.3.0, variáveis estáticas somente poderiam ser inicializadas usando uma expressão constante. A partir do PHP 8.3.0, expressões dinâmicas (por exemplos, chamadas de funções) também são permitidas:

Exemplo #9 Declarando variáveis estáticas

<?php
function foo(){
static
$int = 0; // correro
static $int = 1+2; // correto
static $int = sqrt(121); // correto a partir do PHP 8.3

$int++;
echo
$int;
}
?>

A partir do PHP 8.1.0, quando um método com variáveis estáticas é herdado (mas não sobrescrito), o método herdado não compartilhará as variáveis estáticas do método acima. Isso significa que variáveis estáticas nos métodos agora se comportam da mesma forma que propriedades estáticas.

Exemplo #10 Uso de variáveis estáticas em métodos herdados

<?php
class Foo {
public static function
counter() {
static
$counter = 0;
$counter++;
return
$counter;
}
}
class
Bar extends Foo {}
var_dump(Foo::counter()); // int(1)
var_dump(Foo::counter()); // int(2)
var_dump(Bar::counter()); // int(3), e antes do PHP 8.1.0 int(1)
var_dump(Bar::counter()); // int(4), e antes do PHP 8.1.0 int(2)
?>

Referências em variáveis global e static

O PHP implementa os modificadores static e global para variáveis, em termo de referências. Por exemplo, uma variável global verdadeira, importada dentro do escopo de uma função com a instrução global, na verdade, cria uma referência para a variável global. Isto pode levar a comportamentos imprevisíveis nos seguintes casos:

<?php
function test_global_ref() {
global
$obj;
$new = new stdClass;
$obj = &$new;
}

function
test_global_noref() {
global
$obj;
$new = new stdClass;
$obj = $new;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

O exemplo acima produzirá:

NULL
object(stdClass)#1 (0) {
}

Um comportamento similar se aplica à declaração static. Referências não são armazenadas estaticamente:

<?php
function &get_instance_ref() {
static
$obj;

echo
'Objeto estático: ';
var_dump($obj);
if (!isset(
$obj)) {
$new = new stdClass;
// Atribui uma referencia à variável estática
$obj = &$new;
}
if (!isset(
$obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return
$obj;
}

function &
get_instance_noref() {
static
$obj;

echo
"Objeto estático: ";
var_dump($obj);
if (!isset(
$obj)) {
$new = new stdClass;
// Atribui o objeto à variável estática
$obj = $new;
}
if (!isset(
$obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return
$obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo
"\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

O exemplo acima produzirá:

Objeto estático: NULL
Objeto estático: NULL

Objeto estático: NULL
Objeto estático: object(stdClass)#3 (1) {
  ["property"]=>
  int(1)
}

Este exemplo demonstra que ao atribuir uma referência a uma variável estática, ela não será lembrada quando a função &get_instance_ref() for chamada uma segunda vez.

adicione uma nota

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

up
224
dodothedreamer at gmail dot com
13 years ago
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
if(
$j == 1)
$a = 4;
}
echo
$a;
?>

Would print 4.
up
177
warhog at warhog dot net
18 years ago
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.

<?php

class sample_class
{
public function
func_having_static_var($x = NULL)
{
static
$var = 0;
if (
$x === NULL)
{ return
$var; }
$var = $x;
}
}

$a = new sample_class();
$b = new sample_class();

echo
$a->func_having_static_var()."\n";
echo
$b->func_having_static_var()."\n";
// this will output (as expected):
// 0
// 0

$a->func_having_static_var(3);

echo
$a->func_having_static_var()."\n";
echo
$b->func_having_static_var()."\n";
// this will output:
// 3
// 3
// maybe you expected:
// 3
// 0

?>

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

<?php
class sample_class
{ protected $var = 0;
function
func($x = NULL)
{
$this->var = $x; }
}
?>

I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
up
33
andrew at planetubh dot com
15 years ago
Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>

Thus, complete code looks something like the following (very basic model):

<?php
function safeinclude($filename)
{
//This line takes all the global variables, and sets their scope within the function:
foreach ($GLOBALS as $key => $val) { global $$key; }
/* Pre-Processing here: validate filename input, determine full path
of file, check that file exists, etc. This is obviously not
necessary, but steps I found useful. */
if ($exists==true) { include("$file"); }
return
$exists;
}
?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course. In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
up
10
gried at NOSPAM dot nsys dot by
8 years ago
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

<?php

error_reporting
(E_ALL);

$GLOB = 0;

function
test_references() {
global
$GLOB; // get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB
$test = 1; // declare some local var
$GLOBALS['GLOB'] = &$test; // make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test

$GLOB = 2; // set new value to global variable via earlier set local representation, write to old address

echo "Value of global variable (via local representation set by keyword global): $GLOB <hr>";
// check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)

echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] <hr>";
// check global variable using superglobal array => 1 (got value of local variable $test, new address was used)

echo "Value ol local variable \$test: $test <hr>";
// check local variable that was linked with global using superglobal array => 1 (its value was not affected)

global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $test
echo "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";
// check global variable via local representation => 1 (also value of local variable $test, new address was used)
}

test_references();
echo
"Value of global variable outside of function: $GLOB <hr>";
// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)
?>
up
20
larax at o2 dot pl
18 years ago
About more complex situation using global variables..

Let's say we have two files:
a.php
<?php
function a() {
include(
"b.php");
}
a();
?>

b.php
<?php
$b
= "something";
function
b() {
global
$b;
$b = "something new";
}
b();
echo
$b;
?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

global $b;
$b = "something";
To Top