Phpstatic static variables
- Function Test ()
- {
- $ W3sky = 0;
- Echo $ w3sky;
- $ W3sky ++;
- }
- ?>
This function sets $ w3sky to 0 and outputs "0" for each call ". Adding $ w3sky ++ to the variable has no effect, because the variable $ w3sky does not exist once the function is exited.
For example, to implement a counting function that does not lose the current count value, you need to define the variable $ w3sky as static and use the php static variable. A simple example of php static variables
- Function Test ()
- {
- Static $ w3sky = 0;
- Echo $ w3sky;
- $ W3sky ++;
- }
- ?>
Every time Test () is called, this function outputs the value of $ w3sky and adds one. Static variables also provide a method for processing recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, because infinite recursion may occur without exit. make sure there are methods to stop recursion. The following simple function recursively counts to 10 and uses the static variable $ count to determine when to stop:
2. example of static variables and recursive functions:
- 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. 3. example of declaring static variables:
- Function foo (){
- Static $ int = 0; // correct
- Static $ int = 1 + 2; // wrong (as it is an expression)
- Static $ int = sqrt (121); // wrong (as it is an expression too)
- $ Int ++;
- Echo $ int;
- }
- ?>
|