To update a global variable within a function in PHP, you need to use the global
keyword. This tells PHP that you want to work with the global variable, rather than creating a local variable with the same name.
Understanding Global Variables in PHP
Global variables are those declared outside of any function or class. By default, they are not directly accessible within functions. The global
keyword provides the necessary link.
Using the global
Keyword
Here's a breakdown of how to use the global
keyword to update a global variable:
-
Declare the Global Variable: Define the variable outside any function.
-
Use the
global
Keyword Inside the Function: Within the function where you want to update the variable, use theglobal
keyword followed by the variable name. -
Modify the Variable: After declaring the variable as global within the function, you can then modify its value.
Example
<?php
// Declare a global variable
$globalVariable = 10;
function updateGlobalVariable() {
// Use the global keyword to access the global variable
global $globalVariable;
// Update the global variable's value
$globalVariable = 20;
}
echo "Before function call: " . $globalVariable . "\n"; // Output: 10
updateGlobalVariable();
echo "After function call: " . $globalVariable . "\n"; // Output: 20
?>
In this example, the global
keyword within the updateGlobalVariable()
function allows the function to directly modify the $globalVariable
that was declared outside the function. Without the global
keyword, $globalVariable
inside the function would be treated as a new, local variable, and the global variable would remain unchanged. According to the reference, the global variable $globalVariable
was initialized with a value.
Alternative Approach: Using the $GLOBALS
Array
Another way to access and update global variables is through the $GLOBALS
superglobal array. This array holds all global variables, indexed by their name.
<?php
$globalVariable = 10;
function updateGlobalVariable() {
$GLOBALS['globalVariable'] = 20;
}
echo "Before function call: " . $globalVariable . "\n"; // Output: 10
updateGlobalVariable();
echo "After function call: " . $globalVariable . "\n"; // Output: 20
?>
This approach achieves the same result as using the global
keyword. It directly accesses the global variable through the $GLOBALS
array and modifies its value.
Summary
Method | Description | Example |
---|---|---|
global Keyword |
Explicitly declares that you are using the global variable within the function. | global $globalVariable; |
$GLOBALS Array |
Accesses global variables through an associative array where the keys are the variable names. | $GLOBALS['globalVariable'] = 20; |