PHP global keyword and variable scope
On PHP the great quantity of variables have a single scope.
Single scope<?php $variable = "hola mundo"; include "archivo.php"; ?>
The variable $varaible is disponible in archive.php except in function. Inside functions variables are in local scope, you can access varaibles inside that function.
When we are using functions, we have 3 different situations in where we can access the parent scope: using referenced parameter; second, using global inside the function to access the variable that is $GLOBALS array; 3 using use in anonymous function.
Local variable<?php function myfunction(){ $local = "this is a local variable"; echo "inside function:".$local; } myfunction(); echo $local;
inside function:this is a local variable Notice: Undefined variable: local in /home/user/scripts/code.php on line 8Check that the variable continues being local
$parent ="text not defined"; function myfunction($local){ $local = "this is a local variable"; echo "inside function:".$local."\n"; } myfunction($parent); echo $parent;
inside function:this is a local variable text not defined
When we change the variable inside the function this one not change the parent variable $local
Parameter passed by reference.
As we see before, when a variable is passed by reference, this will change the parent value if this one is modified.
Example of variable passed by reference:<?php $parent ="text not defined"; function myfunction(&$local){ $local = "this is a local variable"; echo "inside function:".$local."\n"; } myfunction($parent); echo $parent;
inside function:this is a local variable this is a local variable
Now $parent will have the value “this is a local variable”
Using use in Anonymous Functions
Since PHP 7 we can use the term use in anonymus functions that permit us to use a variable from the parent scope.
funcion anonima utilizando use<?php $message ="mort dijo: Hola tu"; $example = function () use ($message): string { return $message; }; echo $example();
Watch that we are using $example() and not $example this is cause that $example is an object(closure).
The keyword global y $GLOBAL
Inside a function, we can use global
world that permit access to the global variable, for example global $a permit us use $GLOBALS[‘a’].
If you execute the following code and take a look at the variable value $a would not be more “hello word”, it would be “Bienvenidos”.
ejemplo usando global<?php function cambioDeTexto(){ global $a; $a = "Bienvenido"; } $a = "hello word"; echo "<p>$a</p>"; cambioDeTexto(); echo "<p>$a</p>";
hello word Bienvenido
In this case $a is a global variable and is in $GLOBALS array. Probably this example makes you wonder
¿single scope are global variables? Lets check that.
single scope variable and $GLOBALS<?php $a = "hola"; echo $GLOBALS["a"];
hola