PHP static local static variables and global static variables summary _php tips

Source: Internet
Author: User

Characteristics of static local variables:

1. Does not change as the function is invoked and exited, however, although the variable continues to exist, it cannot be used. If the function that defines it is invoked again, it can continue to be used, and the value left after the previous call is saved
2. Static local variables are initialized only once
3. Static properties can only be initialized to a character value or a constant, and expressions cannot be used. The system automatically assigns an initial value of 0 (to a numeric variable) or a null character (to a character variable), even if the local static variable is defined without an initial initializer, and a static variable is initially 0.
4. When you call a function multiple times and require the values of certain variables to be preserved between calls, consider the use of static local variables. Although the above goal can be achieved with global variables, global variables sometimes cause unexpected side effects, so it is advisable to adopt local static variables.

Copy Code code as follows:

function test ()
{
static $var = 5; static $var = 1+1; There will be an error.
$var + +;
Echo $var. ' ';
}


Test (); 2
Test (); 3
Test (); 4
Echo $var; Error: notice:undefined Variable:var

About static global variables:

Copy Code code as follows:

The global variable itself is a static storage mode, all global variables are static variables
function Static_global () {
Global $glo;
$glo + +;
echo $glo. ' <br> ';
}

Static_global (); 1
Static_global (); 2
Static_global (); 3
Echo $glo. ' <br> '; 3

So static global variables are not used much.

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.