How to Use Global Variables in PHP Functions
This article explains how to access and modify global variables from
within a PHP function using the global keyword. You will
learn the correct syntax, view practical code examples, and discover an
alternative method using the $GLOBALS superglobal array, as
well as best practices for managing variable scope in your PHP
applications.
Understanding PHP Variable Scope
In PHP, variables defined outside of any function have a global scope. By default, these variables are not directly accessible inside a function. If you try to reference a global variable inside a function without declaring it as global, PHP will treat it as a new, undefined local variable.
To bridge this gap, PHP provides the global keyword.
Using the global
Keyword
To access a global variable inside a function, you must declare the
variable with the global keyword before using it. This
tells PHP to reference the variable from the global scope rather than
creating a new local one.
Syntax:
global $variable_name;Example: Reading a Global Variable
<?php
$website_name = "TechTutorials"; // Global variable
def_show_site_name() {
global $website_name; // Declaring the variable as global
echo "Welcome to " . $website_name;
}
def_show_site_name();
// Output: Welcome to TechTutorials
?>Example: Modifying a Global Variable
When you use the global keyword, any changes made to the
variable inside the function will directly affect the variable in the
global scope.
<?php
$counter = 10; // Global variable
function incrementCounter() {
global $counter;
$counter++; // Modifying the global variable
}
incrementCounter();
echo $counter;
// Output: 11
?>Alternative Method:
Using the $GLOBALS Array
PHP also stores all global variables in an associative array called
$GLOBALS. The keys of this array are the names of the
global variables. You can access and modify global variables directly
through this array without using the global keyword.
Example: Using $GLOBALS
<?php
$user = "Alex";
function greetUser() {
// Accessing the global variable via the $GLOBALS array
echo "Hello, " . $GLOBALS['user'];
}
greetUser();
// Output: Hello, AlexBest Practices and Scope Management
While accessing global variables inside functions is easy, it is generally considered a poor programming practice to overuse them.
- Maintainability: Global variables make code harder to debug because any function can alter the variable’s value at any time.
- Reusability: Functions that rely on global variables cannot be easily reused in other parts of your application.
The Recommended Approach: Instead of using global
variables, pass variables into your functions as
arguments and return the modified values using the
return statement.
<?php
// Recommended approach: Pass by argument
function secureIncrement($value) {
return $value + 1;
}
$count = 5;
$count = secureIncrement($count);
echo $count; // Output: 6
?>