Unlike local variables, a global variable can be accessed in any part of the program. Global Variable Declaration in PHP is quite simple, if we want a variable to be accessible from within a function, we can use the global keyword.
Global Variable can be accessed anywhere in our script, whether inside or outside a function. In order to modify a global variable, it must be explicitly declared to be global in the function in which it is to be modified.
Superglobals are built-in variables which are always available in all scopes throughout the script and hence it is not required to declare global $variable to access them within functions or methods.
These superglobal variables are:
It references all variables available in global scope.
<?php function gvalue(){ $animal = "cow"; echo 'local variable:' .$animal."\n"; echo 'globle variable:'.$GLOBALS[$animal]."\n"; } $animal="horse"; gvalue(); ?>
This will produce following result
local variable: cow globale variable: horse
It is an array which contains information like headers, paths,and script locations.
<?php echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; ?>
This will produce following result
techstrikers.com techstrikers.com
It is an associative array of variables passed to the current script through URL parameters.
<?php echo 'Myself' . htmlspecialchars($_GET["myname"]) . '!'; ?>
Suppose the user has made an entry https://example.com/?myname=Bill
This will produce following result
Myself Bill!
It is an associative array of variables passed to the current script through HTTP POST method.
<?php echo 'I want to meet Mr.' . htmlspecialchars($_POST["hostname"]) . '!'; ?>
Suppose the user has made an entry posted hostname = Jim
This will produce following result
I want to meet Mr. Jim
It is an associative array of variables passed to the current script through HTTP Cookies.
<?php echo 'Myself' . htmlspecialchars($_COOKIE["myname"]) . '!'; ?>
Suppose the "myname" cookie has already been set
This will produce following result
Myself Bill!