PHP Variable Scope
Variable scope describes where in your code a variable can be seen and used, which in PHP depends on whether it is created inside or outside a function.
Every variable in PHP lives within a certain region of the program called its scope. Outside that region the name simply does not exist. Understanding scope prevents a common class of bugs where a variable seems to vanish or unexpectedly holds nothing inside a function.
Local and global scope
A variable defined outside any function has global scope, but it is not automatically available inside functions. A variable defined inside a function has local scope and disappears once the function finishes. By default a function cannot see a global variable, which keeps functions self-contained and predictable.
Local scope isolates variables
<?php
$message = "outside"; // global
function show() {
// $message is NOT visible here
$message = "inside"; // this is a separate local variable
echo $message;
}
show(); // prints: inside
echo $message; // prints: outside
?>The global keyword
When a function genuinely needs a global variable, you can pull it in with the global keyword. This tells PHP to use the existing global variable rather than create a new local one. The same variable is also available through the built-in $GLOBALS array.
Accessing a global variable two ways
<?php
$counter = 10;
function increase() {
global $counter;
$counter++;
echo $counter; // 11
echo $GLOBALS['counter']; // 11
}
increase();
?>Static variables
Normally a local variable is destroyed when its function ends. Declaring it static tells PHP to keep its value between calls, while still hiding it from the rest of the program. This is useful for counters or caches that must remember state across multiple calls.
A static variable remembers its value
<?php
function tick() {
static $count = 0;
$count++;
echo $count;
}
tick(); // 1
tick(); // 2
tick(); // 3
?>- Function parameters are local variables scoped to that function.
- Use global or $GLOBALS only when passing arguments is impractical.
- Prefer static for values that must survive between calls to one function.
- Keeping scope narrow makes functions easier to reuse and debug.