Static Variables

A static variable is a variable that retains its value across multiple function calls. Unlike regular variables, which are created and destroyed each time a function is called, static variables are initialized only once and persist throughout the entire execution of the script.

To declare a static variable in PHP, you need to use the static keyword inside a function.

Static variables are commonly used when you want to keep track of certain information across function calls without the need to use global variables or properties. They are especially useful for counters, accumulators, caching, and memoization. However, it’s essential to use them judiciously and avoid excessive reliance on them, as they can make code harder to maintain and understand if used indiscriminately.

Static variables may be refactored as a global variable or a property.

Static variables may be declared only once, starting with PHP 8.3. Until that version, it is a best practice to only declare them once.

Static variables may use any PHP expressions to define their default value. That value is used when the variable is used for the first time.

<?php

function counter() {
    static $count = 0;

    return ++$count;
}

counter(); // print 1
counter(); // print 2

?>

Documentation

See also Static Variables and Methods, 5 usages of static keyword in PHP, PHP Static Variables

Related : Variables, Variable Variables