PHP Variable Scope: Global and Local Variables with Examples
In PHP, the scope of a variable determines where it can be accessed or used. Variables have different scopes depending on where they are declared. The two main types are Global and Local variables.
Global Variables
lobal variables in PHP are declared outside any function and are accessible throughout the script. However, to use them inside a function, you must use the global keyword.
- Declared outside of any function.
- Accessible anywhere outside functions.
- To use them inside a function, you must use the
globalkeyword.
<?php
$globalVar = "Hello"; // Global variable
function displayMessage()
{
global $globalVar; // Access global variable inside function
echo $globalVar;
}
displayMessage(); // Output: Hello
?>
Local Variables
Local variables in PHP are declared inside a function and can only be accessed within that function. They are created when the function is called and destroyed when it ends.
- Declared inside a function.
- Can only be accessed within that function.
- They are created when the function starts and destroyed when it ends.
<?php
function showMessage()
{
$localVar = "Hello World"; // Local variable
echo $localVar;
}
showMessage(); // Output: Hello World
// echo $localVar; // This will cause an error (undefined variable)
?>
Difference between Local & Global Variable
| Aspect | Global Variable | Local Variable |
|---|---|---|
| Declaration | Outside any function | Inside a function |
| Accessibility | Entire script (with global keyword in functions) |
Only within the function |
| Lifetime | Exists as long as the script runs | Exists only during the function execution |
| Use case | Shared data across multiple functions | Temporary data for specific functions |