Variables inside a function are local unless imported with global (avoid) or accessed via superglobals. Prefer passing arguments and returning values over mutating globals.
Local scope
function demo(): void {
$x = 1; // local
}
Static locals
function counter(): int {
static $count = 0;
return ++$count;
}
static retains value between calls—useful for cheap memoization or id generators inside one request, not for shared state across requests.
Closures and use
$factor = 2;
$mul = function (int $n) use ($factor): int {
return $n * $factor;
};
Self-check
- Why avoid
global $configin functions? - Does a static variable persist across HTTP requests?