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

This will produce following result

2. $_SERVER

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

PHP $_SERVER Example

This will produce following result

3. $_GET

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

PHP $_GET Example

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

This will produce following result

4. $_POST

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

PHP $_POST Example

Suppose the user has made an entry posted hostname = Jim

This will produce following result

5. $_COOKIE

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

PHP $_COOKIE Example

Suppose the "myname" cookie has already been set

This will produce following result