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
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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.