Another important feature of the scope of variables in PHP is the static variable (the statics variable). Static variables exist only in the local function domain and are initialized only once, and when the program executes away from this scope, its value does not disappear, and the result of the last execution is used.
Take a look at the following example:
<?php function Test () {$w 3sky = 0; echo $w 3sky; $w 3sky++;}?>
Each call to this function sets the value of $w 3sky to 0 and outputs "0". Adding a variable to the $w 3sky++ has no effect, because once exiting this function the variable $w 3sky does not exist. To write a count function that does not lose this count value, define the variable $w 3sky as static (static):
As follows:
<?php function Test () {static $w 3sky = 0; echo $w 3sky; $w 3sky++;}?>
Each call to test () of this function outputs a value of $w 3sky and adds one.
Static variables also provide a way to handle recursive functions. A recursive function is a method of calling itself. Be careful when writing recursive functions, as there may be infinite recursion and no exits. Be sure there is a way to abort recursion. The following simple function recursively counts to 10, using a static variable $count to determine when to stop:
Examples of static variables and recursive functions:
<? PHP function Test () {static $count = 0; $count + +; echo $count; if ($count <) {Test ();} $count--;}?>
Note: Static variables can be declared according to the example above. If you assign a value to a declaration with the result of an expression, it causes a parse error.
Example of declaring a static variable:
<? PHP 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; }?>