The scope of the global variable is defined at the end of the source file, the storage period is defined and the memory is allocated, and the program releases memory after exiting;
Local variable scope is local, storage period is defined after allocating memory, exit scope after releasing memory, global variable defaults to static variable, local variable defaults to automatic variable, can be declared as static variable, static variable and automatic variable is the difference between storage period, The storage period of a static variable is that the memory space exists during the program run, the program exits before it is released, and the automatic variable memory space exists within the scope and is released after the scope is exited.
Characteristics of static local variables:
Does not change with the invocation and exit of the function, although the variable continues to exist but cannot be used. If the function that defines it is called 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. A static property can only be initialized to a character value or a constant and cannot be used with an expression. Even if the local static variable is defined without an initial value, the system automatically assigns the initial values of 0 (to numeric variables) or null characters (to character variables), and the static variable is initially 0.
4. Consider using static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls. Although this can be achieved with global variables, global variables sometimes cause unintended side effects, so it is advisable to use local static variables. The code is as follows:
function test () { static $var = 5; Static $var = +, will error $var + +; Echo $var. ' ';} Test (); 2test (); 3test (); 4echo $var; Error: notice:undefined Variable:var
about static global variables:
The code is as follows:
The global variable itself is the static storage mode, all global variables are static variable function Static_global () { global $glo; $glo + +; echo $glo. ' <br> ';} Static_global (); 1static_global (); 2static_global (); 3echo $glo. ' <br> '; 3
So static global variables are not used much.
The above is what I put to everyone in PHP static variables and global variables, we hope that in the future will be helpful.
Related articles:
Variable scope and global variables for PHP (text tutorial)
A trick is done, PHP in the closure function inside the use of the method and the difference, as well as the meaning of & reference for you to answer in detail
Learn more about PHP class, method keyword Tutorials