As I have discussed in this post that we can not access global variables inside a function as it's outside of their scope.
But there is a way to do that. We can use reserved keyword "global" inside a function to access their values assigned outside.
Let's take a look at this example.
<?php
$x = 5;
$y = 5;
function globVar() {
global $x, $y;
$y = $x + $y;
}
globVar(); // run function
echo $y; // output the new value for variable $y
echo "<p>As you can see the value of variable y has changed even if we performed the calculation inside the function</p>"
;?>
Take a look at the results of the code above in the DEMO link provided at the end of this article.
We can store the global variables in PHP. PHP provided an array to store those values which is called $GLOBALS[index], where index will be the name of the variable we want it to hold.
Also, we can access this array from inside the function as well as we can update the values of global variables directly.
Take a look at the example below:
<?php
$a = 5;
$b = 10;
function globVar2() {
$GLOBALS['a'] = $GLOBALS['b'] + $GLOBALS['a'];
}
globVar2();
echo $a;
echo "<p>As you can see the value of variable a has changed even if we performed the calculation on the GLOBALS[a] inside the function. Checkout the code in the article from the link above.</p>"
?>
functions Global variables