Home > Article > Backend Development > PHP static static variables
Static variables only exist within the function scope, that is to say, static variables only live on the stack. Generally, variables within functions will be released after the function ends, such as local variables, but static variables will not. That is to say, the value of the variable will be retained the next time this function is called.
As long as you add the keyword static before a variable, the variable becomes a static variable.
<?php function test() { static $nm = 1; $nm = $nm * 2; print $nm."<br />"; } // 第一次执行,$nm = 2 test(); // 第一次执行,$nm = 4 test(); // 第一次执行,$nm = 8 test(); ?>
Program running results:
2 4
8
After the function test() is executed, the value of the variable $nm is saved.
Static properties are often used in classes, such as static members and static methods.
Program List: Static members of the class
The static variable $nm belongs to the class nowamagic, not to an instance of the class. This variable is valid for all instances.
:: is the scope limiting operator. The self scope is used here instead of the $this scope. The $this scope only represents the current instance of the class, and self:: represents the class itself.
view source
print?
<?php class nowamagic { public static $nm = 1; function nmMethod() { self::$nm += 2; echo self::$nm . '<br />'; } } $nmInstance1 = new nowamagic(); $nmInstance1 -> nmMethod(); $nmInstance2 = new nowamagic(); $nmInstance2 -> nmMethod(); ?>
Program running result:
3
5