Static variables exist only within the scope of the function, and static variables live only on the stack. General function variables are released after the function ends, such as local variables, but static variables do not. The value of the variable is preserved the next time the function is called.
Basic usage of static variables
1. Defining static variables in a class
[Access modifier] static $ variable name;
2. How to access static variables
If there are two methods to access in a class self::$ static variable name, class Name:: $ static variable name
If you are accessing outside the class: There is a method class name:: $ static variable name
Example
Copy CodeThe code is as follows:
Class child{
Public $name;
This 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;
echo $this->name. " Added snowmen game ";
}
}
Create three children
$child 1=new Child ("Li Kui");
$child 1->join_game ();
$child 2=new Child ("Zhang Fei");
$child 2->join_game ();
$child 3=new Child ("Tang priest");
$child 3->join_game ();
See how many people are playing games
echo "
Have this. " Child:: $nums;
http://www.bkjia.com/PHPjc/743925.html www.bkjia.com true http://www.bkjia.com/PHPjc/743925.html techarticle static variables exist only within the scope of the function, and static variables live only on the stack. General function variables are released after the function ends, such as local variables, but static variables do not. ...