| In PHP, common global variables and superglobal variables are both used to store data that can be accessed across different parts of a script, but there are some key differences in how they are defined, accessed, and used. Key Differences - Scope and Accessibility:
- Superglobal Variables: These are predefined by PHP and are accessible from any part of the code, regardless of scope. You do not need to use the
global keyword to access them inside functions or methods. - Common Global Variables: These are user-defined variables that are declared in the global scope. To access them inside functions or methods, you need to explicitly declare them as
global.
- Built-In vs. User-Defined:
- Superglobal Variables: These are predefined by PHP and are automatically available across all scopes (e.g.,
$_GET, $_POST, $_SESSION, etc.). - Common Global Variables: These are variables that you define yourself, and they are only available in the global scope unless explicitly made accessible within a function using the
global keyword.
Example of Common Global Variable Let’s see how a common global variable works and how it differs in usage from superglobals. Defining and Using a Common Global Variable <?php
// Declaring a common global variable
$greeting = "Hello, World!";
function sayGreeting() {
// To access a common global variable within a function, use the global keyword
global $greeting;
echo $greeting;
}
sayGreeting(); // Outputs: Hello, World!
?>
In this example: $greeting is a common global variable.- Inside the
sayGreeting function, we use global $greeting; to access $greeting.
Without the global Keyword If you try to access $greeting without declaring it as global, PHP will treat it as a local variable within that function and throw an error or return null (if $greeting is used but never defined locally within the function). <?php
$greeting = "Hello, World!";
function sayGreeting() {
echo $greeting; // This will produce an error or output nothing
}
sayGreeting();
?>
Summary - Superglobal Variables: Predefined by PHP, accessible from any scope without extra syntax.
- Common Global Variables: User-defined, accessible in the global scope. To use them inside functions or classes, you must declare them as
global.
Using global effectively allows you to access global data in functions, but if you need global access everywhere without declaring global repeatedly, superglobals are often the better option. PHP offers nine superglobal variables: $_GET, $_POST, $_REQUEST, $_COOKIE, $_SESSION, $_FILES, $_ENV, $_SERVER, and $GLOBALS. These variables are accessible from anywhere within a script without the need for explicit declaration or global keyword. They store information about the current request, environment, user session, server configuration, and uploaded files, offering a convenient way to access and manipulate data across different parts of a PHP application. |