The use of the PHP static keyword in a function

Source: Internet
Author: User
Tags parse error

As for properties and methods declared as static in a class, this does not describe
Another important feature of the scope of variables in PHP is the static variable (the statics variable). Static variables exist only in the local function domain and are initialized only once, and when the program executes away from this scope, its value does not disappear, and the result of the last execution is used.

function test ()
{
$tVar = 10;
Echo $tVar;
$tVar + +;
}

Each call to the above function sets the value of the $tVar to 10 and outputs "10". Adding a variable to the $tVar + + has no effect, because the variable $tVar does not exist once you exit the function. To write a count function that does not lose this count value, define the variable $tVar as static (static):

function test ()
{
static $tVar = 10;
Echo $tVar;
$tVar + +;
}

Each call to test () above will output the value of $tVar and add 1.

If you assign a value to a declaration with the result of an expression, it causes a parse error. As follows:

function test ()
{
static $tVar = 10+1; Error
Echo $tVar;
$tVar + +;
}


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 and no exits. Be sure there is a way to abort recursion. The following simple function recursively counts to 10, using a static variable $AA to determine when to stop: the following:
function TT ()
{
static $AA = 0;
Echo ' This is TT '. $aa. "<br/>";
$aa + +;
if ($aa < 10)
{
TT ();
}
$AA--; Let it end with the same value as the initialization, preventing the call from being called again to preserve the previously invoked results
}

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.