Home > Article > Backend Development > PHP global keyword, phpglobal keyword_PHP tutorial
global keyword is used to access global variables inside a function.
<?php $x = 5; $y = 10; function myTest(){ global $x,$y; $x = $x+$y; } myTest(); echo $x; //15
PHP stores all global variables in an array named $GLOBALS[index]. Index saves the name of the variable. This array can be accessed inside the function, or global variables can be updated directly;
The above example can be rewritten as follows:
<?php $x = 5; $y=10; function myTest(){ $GLOBALS['x'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $x; //15