Home > Article > Backend Development > Basic usage example code of static variables in php
What is staticstaticvariable? (The following is the understanding in C language)
Static variable type specifier is static.
Static variables belong to the static storage method, and their storage space is the static data area in the memory (storage units are allocated in the static storage area). The data in this area occupies these storage spaces throughout the running of the program. (It is not released during the entire running of the program), and it can also be considered that its memory address remains unchanged until the end of the entire program (on the contrary, auto automatic variables, that is, dynamic local variables, belong to the dynamic storage category and occupy dynamic storage space. Functions Released after the call is completed). Although static variables always exist throughout the execution of the program, they cannot be used outside its scope.
In addition, variables belonging to the static storage method are not necessarily static variables. For example: Although external variables (referred to as global variables in PHP) are static storage methods, they are not necessarily static variables. They must be defined by static before they can become static external variables, or static global variables.
All global variables are static variables, and local variables are local static variables only when they are defined with the type modifier static.
Static variables can be applied anywhere. Once the application is successful, it will no longer accept other similar applications.
Static variables do not mean that they cannot change the value. The amount that cannot change the value is called a constant. The value it holds is mutable, and it will remain up-to-date. It is said to be static because it does not change as the function is called and exits. That is, if we assign a certain value to a static variable the last time the function is called, the value will remain unchanged the next time the function is called. Example
The code is as follows:
class Child{ public $name; //这里定义并初始化一个静态变量 $nums public static $nums=0; function construct($name){ $this->name=$name; } public function join_game(){ //self::$nums 使用静态变量 self::$nums+=1; echo $this->name."加入堆雪人游戏"; } } //创建三个小孩 $child1=new Child("李逵"); $child1->join_game(); $child2=new Child("张飞"); $child2->join_game(); $child3=new Child("唐僧"); $child3->join_game(); //看看有多少人玩游戏 echo "<br/> 有这".Child::$nums;
The above is the detailed content of Basic usage example code of static variables in php. For more information, please follow other related articles on the PHP Chinese website!