Variable Scope
A variable created inside a function is local. Functions cannot see outside variables unless you use the global keyword or pass them in. A static variable keeps its value between calls. Prefer parameters and return values over global.
Example
$total = 10;
function noAccess() {
return isset($total) ? "sees it" : "cannot see it";
}
echo noAccess(), "\n";
function withGlobal() {
global $total;
return $total + 1;
}
echo withGlobal(), "\n";
function counter() {
static $n = 0;
return ++$n;
}
echo counter(), counter(), counter(), "\n";Result
cannot see it 11 123
Exercise
Keep a value between calls.
function f() { $n = 0; }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.