A value set in a variable, in many cases, need to switch over between different scopes within the application. For example, a product code that needs to be used in different situations needs to be rescued from the bank several times, thus compromising the performance of the application as a whole. That would be a problem if a compatible solution did not exist. In PHP, you can use the $GLOBALS superglobal variable to resolve this scenario.
This associative array stores variables that can be globally used within the application, this means that anywhere the application can access its information or modify them. Next, a practical example of using this feature will be presented:
<?php
function test() {
$foo = “Local”;
echo ‘$foo on the global scope: ‘ . $GLOBALS[“foo“] . “n”;
echo ‘$foo on the global scope: ‘ . $foo . “n”;
}
$foo = “Global Example”;
test();
?>
Information printed on screen:
$foo on the global scope: Global Example
$foo on the current scope: Local
In this simple example it is possible to understand the applicability of the $ GLOBALS array. In the method, we have created two types of variables with the same name: one created in local scope and another using the feature. Note that you can access the global variable outside the local scope and add to it a value that can later be modified or recovered.
Any type of information can be stored in the array $ GLOBALS, but there is a peculiarity that needs to be taken into account. Server resources are used for the variable to be stored. Thus, loading a whole object, for example, may not be the best choice because of the application and the object size and the number of concurrent users that the application will have to bear.
Despite being a facilitator resource, the variable $ GLOBALS must be used with caution, always striving for the performance of the application and taking into account all the stress points that may be identified.
Check out more content on our blog!
Learn all about Scriptcase.
You might also like…