Detailed explanation of how to use static variables in php_PHP tutorial

WBOY
Release: 2016-07-21 15:37:13
Original
672 people have browsed it

Take a look at the following example:

Copy code The code is as follows:

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

Every time this function is called 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 code The code is as follows:

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

Every time this function calls Test(), it 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;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321999.htmlTechArticleLook at the following example: Copy the code The code is as follows: ?php function Test() { $w3sky = 0; echo $w3sky; $w3sky++; } ? Each time this function is called, it will set the value of $w3sky to 0 and output "...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!