Global variables are variables that can be accessed from anywhere in a script. There are two common ways to use them:
1. Using the global Keyword:
Variables declared outside a function are not directly accessible inside a function. Use the global keyword to access them.
<?php
$name = "John";
function displayName() {
global $name;
echo $name;
}
displayName();
?>2. Using the $GLOBALS Array:
PHP stores all global variables in the associative array $GLOBALS.
<?php
$x = 10;
$y = 20;
function add() {
echo $GLOBALS['x'] + $GLOBALS['y'];
}
add();
?>PHP Superglobal Variables:
PHP provides built-in global arrays called superglobals, which are available in all scopes without using
| Superglobal | Description |
|---|---|
$_GET | Retrieves data sent via URL parameters. |
$_POST | Retrieves data sent via HTML forms (POST method). |
$_REQUEST | Contains data from GET, POST, and COOKIE. |
$_SESSION | Stores session variables. |
$_COOKIE | Stores cookie values. |
$_SERVER | Contains server and execution environment information. |
$_FILES | Contains uploaded file information. |
$_ENV | Contains environment variables. |
$GLOBALS | Contains all global variables. |