PHP Scope & Variable Lifetime
In this page:
Understanding Local Scope
A variable created inside a function exists only within that function's own execution — it's invisible to code outside, and calling the function again starts with a fresh, empty version of that variable rather than remembering anything from the previous call.
Example: Understanding Local Scope
<?php
function counter() {
$count = 0;
$count++;
echo $count . "\n";
}
counter();
counter();
?>
Login to try C/C++/Java/PHP code in the editor
Understanding Global Scope
A variable created at the top level of a script, outside any function, is global — but that global scope isn't automatically available *inside* a function. You have to explicitly declare global $variableName; inside the function body before you can read or modify it there.
Example: Understanding Global Scope
<?php
$total = 100;
function showTotal() {
global $total;
echo $total;
}
showTotal();
?>
Login to try C/C++/Java/PHP code in the editor
The GLOBALS Superglobal Array
PHP mirrors every global variable into a superglobal array called $GLOBALS, accessible from inside any function without needing the global keyword — $GLOBALS[count] reads or writes the same variable that global $count; would give you access to.
Example: The GLOBALS Superglobal Array
<?php
$count = 5;
function showCount() {
echo $GLOBALS['count'];
}
showCount();
?>
Login to try C/C++/Java/PHP code in the editor
Static Variables
Marking a variable static inside a function makes it retain its value between separate calls to that function, instead of resetting to its initial value each time — useful for something like a counter that needs to remember how many times the function has run so far.
Example: Static Variables
<?php
function increment() {
static $count = 0;
$count++;
echo $count . "\n";
}
increment();
increment();
increment();
?>
Login to try C/C++/Java/PHP code in the editor
Parameter Variable Scope
A function's own parameters behave exactly like local variables: they receive whatever the caller passed in, exist only for the duration of that single call, and vanish the moment the function finishes and returns.
Example: Parameter Variable Scope
<?php
function greet($name) {
echo "Hello, $name";
}
greet("Alice");
// $name does not exist here, outside the function
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: