InThis function is of little use because the value of $w 3sky is set to 0 and output "0" each time it is called. Adding a variable to a $w 3sky++ has no effect, because once you exit 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:
Example using PHP static variable statics
- < ? PHP
- function Test () {
- Static $ W3sky 0;
- echo $w 3sky;
- $w 3sky++;
- }
- ?>
Now, each call to the Test () function outputs the value of $w 3sky and adds one.
Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. You must ensure that there is sufficient method to abort the recursion. This simple function recursively counts to 10, using a static variable $count to determine when to stop:
Example PHP static variable statics and recursive functions
- < ? PHP
- function Test () {
- Static $ Count 0;
- $count + +;
- Echo $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 declaration PHP static variable static
- < ? 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;
- }
- ?>
http://www.bkjia.com/PHPjc/446285.html www.bkjia.com true http://www.bkjia.com/PHPjc/446285.html techarticle This function is of little use, since the value of $w 3sky is set to 0 and output "0" each time it is called. Adding a variable to a $w 3sky++ has no effect, because once exiting this function the variable ...