Static variables exist only within the scope of a function, and static variables live only on the stack. Normal variables are released after the function ends, such as local variables, but static variables do not. The next time the function is called, the value of the variable is preserved.
The basic usage of static variables
1. Define static variables in the class
[Access modifier] static $ variable name;
2. How to access static variables
If there are two ways to access self::$ static variable names in a class, class name:: $ static variable name
If you are accessing outside the class: There is a method class name:: $ static variable name
Example
Copy Code code as follows:
class child{
public $name;
//Here defines and initializes a static variable $nums
public static $nums = 0;
function __construct ($name) {
$this->name= $name;
}
Public function Join_game () {
//self:: $nums using static variables
Self:: $nums +=1; The
Echo $this->name. Add snowmen Game ";
}
}
//Create three children
$child 1=new Child ("Likui");
$child 1->join_game ();
$child 2=new Child ("Zhang Fei");
$child 2->join_game ();
$child 3=new Child ("Tang's Monk");
$child 3->join_game ();
//See how many people play the game
Echo <br/> have this. Child:: $nums;