Introduction to PHP Global variables
Definition
In PHP, global variables are variables that are defined outside of any function or class, and can be accessed and modified from any scope within a script.
List of built-in global variables:
PHP has several built-in global variables. Some of the most commonly used global variables include:
$_GET
: An array that contains data passed to the script via the HTTP GET method.$_POST
: An array that contains data passed to the script via the HTTP POST method.$_SERVER
: An array that contains information about the server and the current script, such as the server name, the client's IP address, and the script's file name.$_SESSION
: An array that contains data that is stored across multiple page requests within a user's session.$_COOKIE
: An array that contains data passed to the script via HTTP cookies.$_FILES
: An array that contains information about files that have been uploaded to the server via the HTTP POST method.$_ENV
: An array that contains information about the environment variables set on the server.$_REQUEST
: An array that contains data passed to the script via both the GET and POST methods.$_GLOBALS
: An array that contains all global variables available to the script.$GLOBALS
: A superglobal variable that contains all global variables available to the script, it is same as$_GLOBALS
.
Examples
<?php
// Declare a global variable
$global_variable = "Hello World";
// Function that uses the global variable
function myFunction() {
global $global_variable;
echo $global_variable;
}
// Function call
myFunction(); // Output: Hello World
?>
In this example, the variable $global_variable
is declared outside of any function. The function myFunction()
uses the global
keyword to access this variable within the function. Without the global
keyword, the function would not be able to access the variable and would produce an error.
Best Practices
Try to avoid using global variables and instead pass variables as function arguments or use object-oriented programming techniques to access shared data.
To make it clear which variables are global, it is best practice to declare them at the top of the script, before any functions or classes are defined.
To make it easy to understand which variable is being used and for what purpose, it is important to use clear and descriptive variable names.
To make it clear which variables are global, it is best practice to use a naming convention, such as prefixing global variables with the string "g_".
The global keyword should be used with care, as it can make code difficult to understand and maintain.
Be aware of the scope of global variables and the impact that changes to them can have on the rest of the script.
If you have to use global variables use const or define to make sure that variables are read-only and cannot be changed.
Superglobals like
$_POST
and$_GET
should be used only in the scope they were intended for and not used as global variables.