Access a global variable in a PHP function
In PHP, you can access a global variable within a function by using the global keyword.
In PHP, you can access a global variable within a function by using the global keyword. For example:
Example of accessing a global variable in a PHP function
php— editable, runs on the server
Info
Watch a video 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.