Scope¶
Variable Scope¶
Documentation link
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
<?php
$a = 1;
include 'b.inc';
?>
$a
variable will be available within the included b.inc
script.
However, within user-defined functions a local function scope is introduced.
Any variable used inside a function is by default limited to the local function scope.
For example:
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
$a
variable, and it has not been assigned a value within this scope.
You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition.
This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
Refer to the documentation to read about static
and global
variables
Globals¶
Documentation link
An associative array containing references to all variables which are currently defined in the global scope of the script.
The variable names are the keys of the array.
Superglobals¶
Documentation link
Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script.
There is no need to do global $variable; to access them within functions or methods.