Home  >  Article  >  Backend Development  >  Detailed explanation of php static static variable tutorial

Detailed explanation of php static static variable tutorial

WBOY
WBOYOriginal
2016-07-25 08:52:41758browse
? & Lt;? Php
Function test () {
$ w3sky = 0;
    echo $ w3sky;
  1. $ w3sky ++;
  2. }
  3. ? & 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.
  4. 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
  1. 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. 2. Examples of static variables and recursive functions:
function Test() {
static $count = 0;

$count++;

echo $count;

if ($count < 10) {

Test();
}
$count--;
    }
  1. ?>
  2. Copy code
  3. 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:
  4. 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;

}
?>
  1. Copy code
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn