Static Variables

A static variable keeps its value between function calls.

Syntaxstatic $counter = 0;

Normally a local variable is destroyed when a function finishes. If you declare it with the static keyword, PHP remembers its value for the next call.

This is useful for counters and other values that need to persist across calls without being global.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Counting how many times a function has run during a single request.
  • Caching an expensive computed value so it is only calculated once.
  • Generating incrementing ids without exposing a global counter.

More examples

A call counter

static keeps $n between calls instead of resetting it to 0.

Example · php
<?php
function counter() {
    static $n = 0;
    $n++;
    echo $n . " ";
}
counter(); counter(); counter(); // 1 2 3

Cache the first result

The expensive step runs on the first call; later calls reuse the stored value.

Example · php
<?php
function config() {
    static $cache = null;
    if ($cache === null) {
        $cache = "loaded"; // heavy work runs once
    }
    return $cache;
}
echo config();

Without static it resets

A normal local variable is recreated at 0 on every call.

Example · php
<?php
function normal() {
    $x = 0;
    $x++;
    echo $x . " ";
}
normal(); normal(); // 1 1

Discussion

  • Be the first to comment on this lesson.