? & Lt;? Php Function test () { $ w3sky = 0; echo $ w3sky; - $ w3sky ++;
- }
- ? & Gt; The value of $w3sky will be set to 0 and "0" will be output.
Increasing the variable $w3sky++ by one has no effect, because the variable $w3sky does not exist once this function exits.
-
- Example, to implement a counting function that will not lose this count value, to define the variable $w3sky as static, use PHP static variables. Simple example of php static variables
-
-
-
-
function Test() { static $w3sky = 0; echo $w3sky; $w3sky++; } ?>
Copy code-
-
- This function works every time Calling Test() will output the value of $w3sky and add one.
Static variables also provide a way to handle recursive functions. A recursive function is a method that calls itself.
Be careful when writing recursive functions, as they may recurse indefinitely without an exit. Be sure to have a way to abort the recursion. Here is a simple function that recursively counts to 10, using the static variable $count to determine when to stop:
-
- 2. Examples of static variables and recursive functions:
-
-
-
-
function Test() { static $count = 0; $count++; echo $count; if ($count < 10) { Test(); } $count--; } - ?>
-
-
- Copy code
-
-
- Note: Static variables can be declared as shown in the above example.
Assigning it with the result of an expression in a declaration will result in a parsing error.
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; }
|