In PHP global variables are ones defined outside of functions. They can be accessed and have value modified inside or outside of a function.
Global variables are defined like normal ones. But to access them inside functions, we need to use a certain method:
- Use global keyword
- Use array GLOBALS[variable_name]
$num = 100; function updateNum(){ global $num; $num += 200; } updateNum(); echo $num; //output: 300
$brand = 'Samsung'; function showModel(){ if($GLOBALS['brand'] == 'Samsung'){ echo 'Galaxy S21'; } } showModel(); //output: Galaxy S21