Ámbito de las variables

El ámbito de una variable es el contexto en el cual la variable está definida. PHP tiene un ámbito de función y un ámbito global. Cualquier variable difinida fuera de una función está limitada al ámbito global. Cuando se incluye un archivo, el código contenido hereda el ámbito de la variable de la línea en la cual se incluye el archivo.

Ejemplo #1 Ejemplo de una variable de ámbito global

<?php
$a
= 1;
include
'b.inc'; // La variable $a estará disponible en el interior de b.inc
?>

Cualquier variable declarada dentro de una función o una funcíón anónima está limitada al ámbito del cuerpo de dicha función. Sin embargo, las funciones de flecha vinculan las variables desde el ámbito padre haciendo que estén disponibles dentro de la función. Si se incluye un archivo dentro de una función, las variables contenidas en el archivo llamado estarán disponibles como si se hubieran definido dentro de la función que realiza la llamada.

Ejemplo #2 Ejemplo de una variable de ámbito local

<?php
$a
= 1; // ámbito global

function test()
{
echo
$a; // La variable $a no está definida ya que se refiere a una versión local de $a
}
?>

El ejemplo anterior producirá un E_WARNING por una variable no definida (o un E_NOTICE antes de PHP 8.0.0). Esto se debe a la expresión echo hace referencia a una versión local de la variable $a, a la cual no se le ha asignado un valor dentro de su ámbito. Puede que usted note que hay una pequeña diferencia con el lenguaje C, en el que las variables globales están disponibles automáticamente dentro de la función a menos que sean expresamente sobreescritas por una definición local. Esto puede causar algunos problemas, ya que la gente podría cambiar variables globales sin darse cuenta. En PHP, las variables globales deben ser declaradas globales dentro de la función si van a ser utilizadas dentro de dicha función.

La palabra clave global

La palabra clave global se usa para vincular una variable desde el ámbito global a un ámbito local. La palabra clave puede ser usada con una lista de variables o con una sola variable. Una variable local será creada haciendo referendia a una variable global con el mismo nombre. Si no existe la variable global, la variable será creada en el ámbito global y asignado el valor null.

Ejemplo #3 Uso de global

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

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

$b = $a + $b;
}

Suma();
echo
$b;
?>

El resultado del ejemplo sería:

3

Al declarar las variables $a y $b globales dentro de la función, todas las referencias a tales variables se referirán a la versión global. No hay límite al número de variables globales que se pueden manipular dentro de una función.

Un segundo método para acceder a las variables desde un ámbito global es usando el array especial definido por PHP $GLOBALS. El ejemplo anterior se puede reescribir así:

Ejemplo #4 Uso de $GLOBALS en lugar de global

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

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

Suma();
echo
$b;
?>

El array $GLOBALS es un array asociativo con el nombre de la variable global como clave y los contenidos de dicha variable como el valor del elemento del array. $GLOBALS existe en cualquier ámbito, esto ocurre ya que $GLOBALS es una superglobal. Aquí hay un ejemplo que demuestra el poder de las superglobales:

Ejemplo #5 Ejemplo que demuestra las superglobales y el ámbito

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

Nota:

Utilizar una clave global fuera de una función no es un error. Esta puede ser utilizada aún si el fichero está incluido desde el interior de una función.

Uso de variables static

Otra característica importante del ámbito de las variables es la variable estática. Una variable estática existe sólo en el ámbito local de la función, pero no pierde su valor cuando la ejecución del programa abandona este ámbito. Consideremos el siguiente ejemplo:

Ejemplo #6 Ejemplo que demuestra la necesidad de variables estáticas

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

Esta función tiene poca utilidad ya que cada vez que es llamada asigna a $a el valor 0 e imprime un 0. La sentencia $a++, que incrementa la variable, no sirve para nada, ya que en cuanto la función finaliza, la variable $a desaparece. Para hacer una función útil para contar, que no pierda la pista del valor actual del conteo, la variable $a debe declararse como estática:

Ejemplo #7 Ejemplo del uso de variables estáticas

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

Ahora, $a se inicializa únicamente en la primera llamada a la función, y cada vez que la función test() es llamada, imprimirá el valor de $a y lo incrementa.

Las variables estáticas también proporcionan una forma de manejar funciones recursivas. La siguiente función cuenta recursivamente hasta 10, usando la variable estática $count para saber cuándo parar:

Ejemplo #8 Variables estáticas con funciones recursivas

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

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

Antes de PHP 8.3.0, las variables estáticas solo podían ser inicializadas usando expresiones constantes. A partir de PHP 8.3.0, expresiones dinámicas (por ejemplo, llamadas a funciones) también están permitidas:

Ejemplo #9 Declarando variables estáticas

<?php
function foo(){
static
$int = 0; // correcto
static $int = 1+2; // correcto
static $int = sqrt(121); // correcto a partir de PHP 8.3.0

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

Las variables estáticas dentro de funiones anónimas también persisten solo dentro de esa instancia específica de la función. Si la función anónima es recreada en cada llamada, la variable estática será reinicializada.

Ejemplo #10 Variables estácias en funciones anónimas

<?php
function funcionEjemplo($input) {
$result = (static function () use ($input) {
static
$counter = 0;
$counter++;
return
"Entrada: $input, Contador: $counter\n";
});

return
$result();
}

// Las llamadas a funcionEjemplo recrearán la función anónima, por tanto
// la variable estática no retendrá su valor.
echo funcionEjemplo('A'); // Devolverá: Entrada: A, Contador: 1
echo funcionEjemplo('B'); // Devolverá: Entrada: B, Contador: 1
?>

A partir de PHP 8.1.0, cuando un método que usa variables estáticas es heredado (pero no sobrescrito), el método heredado compartirá ahora las variables estáticas con el método padre. Esto significa que las variables estáticas en los métodos ahora se comportan de la misma manera que las propiedades estáticas.

A partir de PHP 8.3.0, las variables estáticas pueden ser inicializadas con expresiones arbitrarias. Esto significa que las llamadas a métodos, por ejemplo, pueden ser usadas para inicializar variables estáticas.

Ejemplo #11 Uso de variables estáticas en métodos heredados

<?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), antes de PHP 8.1.0 int(1)
var_dump(Bar::counter()); // int(4), antes de PHP 8.1.0 int(2)
?>

Referencias con variables global y static

PHP implementa los modificadores static y global para variables en términos de referencias. Por ejemplo, una variable global verdadera importada dentro del ámbito de una función con global crea una referencia a la variable global. Esto puede ser causa de un comportamiento inesperado, tal y como podemos comprobar en el siguiente ejemplo:

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

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

prueba_referencia_global();
var_dump($obj);
prueba_no_referencia_global();
var_dump($obj);
?>

El resultado del ejemplo sería:

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

Un comportamiento similar se aplica a static. Las referencias no son almacenadas estáticamente.

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

echo
'Objeto estático: ';
var_dump($obj);
if (!isset(
$obj)) {
$new = new stdClass;
// Asignar una referencia a la variable estática
$obj = &$new;
}
if (!isset(
$obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return
$obj;
}

function &
obtener_instancia_no_ref() {
static
$obj;

echo
'Objeto estático: ';
var_dump($obj);
if (!isset(
$obj)) {
$new = new stdClass;
// Asignar el objeto a la variable estática
$obj = $new;
}
if (!isset(
$obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return
$obj;
}

$obj1 = obtener_instancia_ref();
$aun_obj1 = obtener_instancia_ref();
echo
"\n";
$obj2 = obtener_instancia_no_ref();
$aun_obj2 = obtener_instancia_no_ref();
?>

El resultado del ejemplo sería:

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

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

Este ejemplo demuestra que al asignar una referencia a una variable estática, esta no es recordada cuando se invoca la funcion &obtener_instancia_ref() por segunda vez.

add a note

User Contributed Notes 5 notes

up
227
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
179
warhog at warhog dot net
19 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
34
andrew at planetubh dot com
16 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
9 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