The use method of static statically variable in PHP _php Foundation

Source: Internet
Author: User
Tags parse error
Take a look at the following example:
Copy Code code as follows:

<?php
function Test ()
{
$w 3sky = 0;
echo $w 3sky;
$w 3sky++;
}
?>

This function sets the value of $w 3sky to 0 and outputs "0" each time it is invoked. Adding a variable to the $w 3sky++ has no effect, because once the function is exited, the variable $w 3sky does not exist. To write a count function that does not lose the value of this count, define the variable $w 3sky as static (static):
As follows:
Copy Code code as follows:

<?php
function Test ()
{
static $w 3sky = 0;
echo $w 3sky;
$w 3sky++;
}
?>

Every call to test () of this 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 method of calling itself. Be careful when writing recursive functions, as there may be infinite recursion, no exits. Be sure to have a way to abort recursion. The following simple function recursive count to 10, using static variable $count to determine when to stop:
Examples of static variables and recursive functions:
Copy Code code as follows:

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

Note: Static variables can be declared according to the example above. If you assign a value to a declaration using the result of an expression, it can cause a parse error.
Declare a static variable example:
Copy Code code as follows:

? Php
function foo () {
static $int = 0;//correct
static $int = 1+2; Wrong (as it is a expression)
Static $int = sqrt (121); Wrong (as it is a expression too)
$int + +;
Echo $int;
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.