PHP static variable static sample code demonstration. This function is useless because $ w3sky is set to 0 and 0 is output every time you call the function. Adding $ w3sky ++ to the variable does not work, because once you exit this function, the variableThis function is useless because $ w3sky is set to 0 and "0" is output every time you call it ". Adding $ w3sky ++ to the variable does not work because $ w3sky does not exist once you exit this function. To write a counting function that does not lose the current count value, you must define the variable $ w3sky as static:
Example of static PHP variables
- < ?PHP
- function Test(){
- static $w3sky = 0;
- echo $w3sky;
- $w3sky++;
- }
- ?>
Now, every time you call the Test () function, the value of $ w3sky is output and added with one.
Static variables also provide a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:
Example of static and recursive functions in PHP
- < ?PHP
- function Test(){
- static $count = 0;
- $count++;
- echo $count;
- if ($count < 10) {
- Test();
- }
- $count--;
- }
- ?>
Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.
Example declaration PHP static variable
- < ?PHP
- function foo(){
- static $int = 0;// correct
- static $int = 1+2; // wrong (as it is an expression_r_r)
- static $int = sqrt(121); // wrong (as it is an expression_r_r too)
- $int++;
- echo $int;
- }
- ?>
This function is useless because $ w3sky is set to 0 and "0" is output every time you call the function ". Adding $ w3sky ++ to the variable does not work, because once you exit this function, the variable...