PHP static local static variables and global static variables summary

  • 2021-01-18 06:22:17
  • OfStack

Static local variable features:

1. It does not change as the function is called and exited, but it cannot be used even though the variable still exists. If the function that defined it is called again, it can be used again, and it retains the value left over from the previous call
2. Static local variables are initialized only once
3. Static properties can only be initialized to a 1 character value or a constant. Expressions cannot be used. Even if local static variables are defined without an initial value, the system automatically assigns an initial value of 0 (for numeric variables) or a null character (for character variables). The static variable has an initial value of 0.
4. When calling a function multiple times and requiring the value of certain variables to be preserved between calls, consider using static local variables. Although global variables can also be used for this purpose, they can sometimes cause unexpected side effects, so local static variables are preferable.


function test()
{
    static $var = 5;  //static $var = 1+1; Would be an error 
    $var++;
    echo $var . ' ';
}

 
test(); //2
test(); //3
test(); //4
echo $var; // Error: Notice: Undefined variable: var

About static global variables:


// Global variables are themselves statically stored , 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.


Related articles: