PHP Global Variable Declaration

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

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:

1. $GLOBALS

It references all variables available in global scope.

PHP $GLOBALS Example

<?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

2. $_SERVER

It is an array which contains information like headers, paths,and script locations.

PHP $_SERVER Example

<?php
	echo $_SERVER['SERVER_NAME'];
	echo "<br>";
	echo $_SERVER['HTTP_HOST'];
	echo "<br>";
?> 

This will produce following result

techstrikers.com
techstrikers.com

3. $_GET

It is an associative array of variables passed to the current script through URL parameters.

PHP $_GET Example

<?php
	echo 'Myself' . htmlspecialchars($_GET["myname"]) . '!';
?> 

Suppose the user has made an entry http://example.com/?myname=Bill

This will produce following result

Myself Bill!

4. $_POST

It is an associative array of variables passed to the current script through HTTP POST method.

PHP $_POST Example

<?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

5. $_COOKIE

It is an associative array of variables passed to the current script through HTTP Cookies.

PHP $_COOKIE Example

<?php
	echo 'Myself' . htmlspecialchars($_COOKIE["myname"]) . '!';
?> 

Suppose the "myname" cookie has already been set

This will produce following result

Myself Bill!