Summary of PHP static local static variables and Global static variables

Source: Internet
Author: User

Summary of PHP static local static variables and Global static variables

The reason why static local variables are used is that they cannot be used externally, but their values are retained when they are not used. Although global variables can be used to implement the same functions, they often cause exceptions.

Static local variables:

 

1. It will not change with the function call and exit. However, although the variable still exists, it cannot be used. If you call a function that defines it again, it can continue to be used and save the value left after the previous call.

2. Static local variables will only be initialized once

3. Static attributes can only be initialized as a character value or a constant, and expressions are not supported. Even if no initial value is assigned to a local static variable, the system automatically assigns the initial value 0 (For numeric variables) or null characters (for character variables). The initial value of the static variable is 0.

4. When you call a function multiple times and require that the values of some variables be retained between calls, you can consider using static local variables. Although global variables can also achieve the above purpose, global variables sometimes cause unexpected side effects, so it is best to use local static variables.

 

 

The Code is as follows:

Function test ()

{

Static $ var = 5; // static $ var = 1 + 1; an error is returned.

$ Var ++;

Echo $ var .'';

}

 

 

Test (); // 2

Test (); // 3

Test (); // 4

Echo $ var; // error: Notice: Undefined variable: var

 

 

Static global variables:

 

The Code is as follows:

// Global variables are static storage, and 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

 

 

Therefore, there are not many static global variables.

 

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.