In PHP, the $GLOBALS superglobal array is an associative array containing references to all variables that are currently defined in the global scope of the script. It is automatically created by PHP and can be accessed from anywhere in the script. The keys of the array are the names of the variables, and the values are the current values of the variables.
Here's an example of how you can use the $GLOBALS array to access a global variable from within a function:
<?php $x = 5; function test() { $GLOBALS['x']++; } test(); echo $x; // Outputs 6 ?>
In this example, the variable $x is defined at the global level and its value is incremented by one when the test() function is called.
You can also use the $GLOBALS array to define new global variables, like this:
$GLOBALS['new_variable'] = 'hello';
It's worth noting that $GLOBALS is an array just like any other, so you can use array functions on it, you can iterate over it, etc. Also, it's not recommended to use $GLOBALS as much as possible, because it makes the code harder to read and understand.
It's important to use global variables carefully, they can cause a lot of confusion, hard to find bugs and make your code hard to test. It's usually better to use function arguments and return values. And when you need to use them, use them with purpose and well commented, so other developers can understand the usage.
Share With Family & Friends