PHP Variables Scope
You can declare a PHP variable anywhere in a script, but that doesn't mean you can use it everywhere. The part of the script where a variable is available is called its scope, and there are three kinds: local, global and static.
Global and Local Scope
Where you declare a variable decides its scope. Declared outside a function, it has global scope and is out of reach inside functions. Declared inside a function, it has local scope and exists only for that function.
Global scope variable
$x is created outside myTest(), so the function can't see it and prints no value. Only the echo outside the function shows 5:
Output: PHP script
<?php
$x = 5;
function myTest() {
echo $x;
}
myTest();
echo $x;
?>
Local scope variable
This time $x is created inside myTest(), so only the function's own echo shows 5. The line outside the function has nothing to print:
Output: PHP script
<?php
function myTest() {
$x = 5;
echo $x;
}
myTest();
echo $x;
?>
The PHP global Keyword
A function can still reach a global variable if you ask for it. Inside the function, write the global keyword before the variable names.
Using the global keyword
With global $x, $y; the function works directly on the outer variables, so the new value of $y is still there when the function ends:
Output: PHP script
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y;
?>
Using the $GLOBALS array
PHP also keeps every global variable in an array named $GLOBALS[index]. A function can read and change them through that array, as this code does:
Output: PHP script
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;
?>
The PHP static Keyword
A function's variables normally vanish once it finishes running. Sometimes, though, you want a local variable to survive until the next call because you still need its value. Just add the static keyword the first time you declare it:
Using the static keyword
Because $x is static, each call picks up where the last one left off, so the output counts 0, 1, 2:
Output: PHP script
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "\n";
myTest();
echo "\n";
myTest();
?>