How can you declare a PHP variable that retains its value between function calls?

Understanding Static Variables in PHP

In PHP, a variable that retains its value between function calls is declared using the static keyword, like so: static $var;. This construct allows the variable $var to preserve its previous value each time the function in which it is defined is called.

Typically, when a function is completed in PHP, all variables local to that function are destroyed. However, when a variable is declared as static, PHP allocates a permanent storage space for it, ensuring its persisted existence and the retention of its previous value for the duration of the entire script execution.

Let's consider a practical example to understand this better.

function count_visits() {
    static $count = 0;
    $count++;
    echo "This function has been visited $count times.\n";
}
count_visits();
count_visits();
count_visits();

In this example, each call to count_visits increments the $count variable by one and displays the new value. The output will be:

This function has been visited 1 times.
This function has been visited 2 times.
This function has been visited 3 times.

Without the static keyword, $count would be reinitialized to zero each time count_visits is called, producing always the same output: "This function has been visited 1 times."

It's important to note that static variables are local to their function. They're not accessible outside the function that declared them, like public or global variables, but neither are they reinitialized every time the function is called, like regular local function variables.

In terms of best practices, static variables should be used sparingly. Although useful for data persistence across function calls, this can make code harder to debug and understand, as it introduces a form of statefulness into function calls which are typically stateless. As with all constructs, understanding their implications is crucial to using them effectively and efficiently.

Do you find this helpful?