0

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>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70

1 Answers1

1

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.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
  • But its not defined inside that function. –  Jan 10 '16 at 16:43
  • @FahadUddin odd wording. What he means is that any variable that is not in a function, loop, etc... are global and accessible everywhere. – Evan Carslake Jan 10 '16 at 16:44
  • No, I skipped the part where he was setting the global variable. My bad for not reading the code properly. I've updated the answer. – Xorifelse Jan 10 '16 at 16:47