This question already has an answer here:
How is $x
and $y
global variables if they don't have global written before them?
<!DOCTYPE html>
<html>
<body>
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
</body>
</html>
</div>
Because they are defined in the global namespace. A variable declared in a function can only be used within that function. You can overrule this by using the global
operator that looks for the variable in the global name space.
function addition() {
global $x, $y;
$GLOBALS['z'] = $x + $y;
}
However the $GLOBALS
variable is a place where all globals are stored. Since you define it in that function the $z
variable is set.