A global variable is a variable that is defined in scope and can cover the included and required areas. (Simply put, I mean php file / function / class)
Here are some examples of how global variables work.
Example 1: a variable declared in scope and used in a function using the global
<?php $a = 1; function add_a() { global $a; $a++; } add_a(); echo $a;
In the above example, we declare the variable $a
and assign it a value of 1
in scope. Then we declare the add_a
function in the same scope and try to increase the value of the variable $a
. The add_a
function is add_a
, and then we echo
$a
variable, expecting the result to display 2
.
Example 2: a variable declared in scope and used in a function using the $GLOBALS
variable
<?php $a = 1; function add_a() { $GLOBALS['a']++; } add_a(); echo $a;
The result from Example 2 above is exactly the same as the result from Example 1.
There is no difference in using the global
and the PHP special variable defined in the $GLOBALS
array. However, both of them have their advantages and disadvantages.
Learn more about $GLOBALS
on the official PHP site $ GLOBALS
If you want to cover the declared scope variable with the included or required scope, see the example below.
Example 3: a.php
file
<?php global $a; $a = 1; require 'b.php'; add_a(); echo $a;
b.php
file
<?php function add_a() { global $a; $a++; }
In the above example, we have a.php
and b.php
. The b.php
file b.php
required in the a.php
file because we use the function declared in the b.php
file. To use the $a
variable in the b.php
file, we must first declare $a
as global for use outside the local scope, and we will do this by first calling global $a
, and then we define a value, for example, $a = 1
. The $ a variable is now available for use anywhere on any included areas, by first invoking global $a
before manipulation.
Static variables Usually found in classes, but in some well-designed PHP projects you can find them in recursive functions. A static variable is a variable that remembers its value and can be reused every time a function or method is called.
Here are some examples of using a static variable.
Example 1: Static Variable in a Function
function add() { static $a = 1; $a++; echo $a; } add();
Example 2: Static variable in a class
class A { public static $a = 1; public static function add() { self::$a++; echo self::$a; } } echo A::$a;
Note that you cannot assign a return value from a function to a static variable. For example, you cannot do static $a = rand()
. See example 3 below on how to assign a return value to a static variable.
Example 3: Assigning a returned variable from a function to a static variable
function add() { static $a; $a = rand(); echo $a; }
Learn more about global and static variables on the official PHP website. Scope of variables