Home > Backend Development > PHP Tutorial > Detailed explanation of how to use static static variables in st patrick day php

Detailed explanation of how to use static static variables in st patrick day php

WBOY
Release: 2016-07-29 08:42:57
Original
1273 people have browsed it

Take a look at the example below:

Copy code The code is as follows:


function Test()
{
$w3sky = 0;
echo $w3sky;
$w3sky++;
}
? >


Every time this function is called, it will set the value of $w3sky to 0 and output "0". Increasing the variable $w3sky++ by one has no effect, because the variable $w3sky does not exist once this function exits. To write a counting function that will not lose this count value, define the variable $w3sky as static:
As follows:

Copy the code The code is as follows:


function Test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>


Every time Test() is called, this function will output the value of $w3sky and increment it by one.
Static variables also provide a way to deal with 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. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Example of static variables and recursive functions:

Copy code The code is as follows:


function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test();
}
$count--;
}
?>


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.
Example of declaring static variables:

Copy code The code is as follows:


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;
}
?>

The above introduces the detailed explanation of the use of static variables in st patrick day php, including the content of st patrick day. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template