The scope of a variable determines where it can be accessed in your code. PHP has three main types of variable scope: local, global, and static.
Local Variables
Variables defined inside a function are local to that function. They cannot be accessed outside the function.
function showNumber() {
$number = 10; // Local variable
echo $number;
}
showNumber(); // Output: 10
// echo $number; // Error: Undefined variable $number
Global Variables
Variables declared outside any function are global. To use a global variable inside a function, you need the global keyword.
$globalNumber = 20;
function displayGlobal() {
global $globalNumber;
echo $globalNumber;
}
displayGlobal(); // Output: 20
Avoid excessive use of global variables, as they can lead to bugs in larger programs.
Static Variables
A static variable retains its value between function calls. This is useful for counting or tracking states.
function counter() {
static $count = 0; // Static variable
$count++;
echo $count;
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3