Access a global variable in a PHP function

In PHP, you can access a global variable within a function by using the global keyword. For example:


$x = 5;
$y = 10;

function add()
  global $x, $y;
  $result = $x + $y;
  return $result;

echo add();

Watch a course Learn object oriented PHP

The function add() uses the global keyword to access the global variables $x and $y, and then adds them together and returns the result. Alternatively you could use $GLOBALS['x'] or $GLOBALS['y'] to access the global variable inside the function.