Back to results for “Scope”
PHP › Functions & Scope

How does the static keyword affect a variable declared inside a function, and how does this differ from a regular local variable?

Intermediate

Answer

A regular local variable inside a function is reset to its initial value every single time the function is called, while a variable declared as static retains its value between separate calls to that same function, meaning the function remembers the variable's value from the previous call rather than starting fresh each time, which can be useful for scenarios like tracking how many times a specific function has been called.
function trackCalls() {
    static $count = 0;
    $count++;
    return $count;
}
echo trackCalls();
echo trackCalls();
Real-world example A rate limiting function uses a static variable to keep track of how many times it has been called within the current script execution, without needing an external variable or class property to maintain that count between calls.

Common follow-ups: How does a static variable inside a function differ from a static property on a class?;Is a static variable's value shared across different requests in a typical web application?