Home > Article > Backend Development > What is the static variable mechanism of PHP functions?
The static variable mechanism of PHP functions allows variables to retain their values between function calls, thereby achieving the following functionality: Preserving state between function calls. Avoid creating duplicate variables. Simplify the code.
Static variable mechanism of PHP function
Introduction
Static variable is a A special variable scope that exists only inside a function and retains its value each time the function is called. This is different from regular variables, which are reset after each function call.
Syntax
To declare a static variable, just precede the variable with the static
keyword, as shown below:
function foo() { static $counter = 0; $counter++; echo $counter; }
Practical Case
Suppose we want to create a function that prints an incrementing counter every time it is called. Using static variables, we can easily achieve this:
function getCounter() { static $counter = 0; $counter++; return $counter; } echo getCounter(); // 输出 1 echo getCounter(); // 输出 2 echo getCounter(); // 输出 3
Difference from non-static variables
Advantages
Note
The above is the detailed content of What is the static variable mechanism of PHP functions?. For more information, please follow other related articles on the PHP Chinese website!