Global variables refer to any variable defined outside the function. Global variables are accessible from any part of the script, i.e. inside and outside the function.
There are two ways to access a global variable inside a function:
- Using the global keyword
- Using the array GLOBALS[var_name]: It stores all global variables in an array called GLOBALS[var_name]. var_name is the name of the variable. This array is also accessible from functions and can be used to perform operations on global variables directly.
How to declare a global variable in PHP
<?php
$a = 1;
$b = 2;
function fun()
{
global $a, $b;
$b = $a + $b;
}
fun();
echo $b;
?>
Output:
3