Basic usage of static variables in php_PHP tutorial

WBOY
Release: 2016-07-13 10:35:32
Original
664 people have browsed it

Static variables only exist within the function scope, and 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. The next time this function is called, the value of the variable will be retained.

Basic usage of static variables

1. Define static variables in the class
[Access modifier] static $ variable name;
2. How to access static variables
If accessed in the class, there are two methods self::$static variable name, classname::$static variablename
If accessed outside the class: there is one method classname::$static variablename

Example

Copy code The code is as follows:

class Child{

public $name;
//Define and initialize a static variable $nums here
public static $nums=0;
function __construct($name){

$this->name=$name;
}

public function join_game(){

//self::$nums uses static variables
self::$nums+=1;

echo $this ->name."Join the snowman building game";

}


}

//Create three children

$child1= new Child("Li Kui");
$child1->join_game();
$child2=new Child("Zhang Fei");
$child2->join_game();
$child3=new Child("Tang Monk");
$child3->join_game();

//See how many people play the game
echo "
Yes This".Child::$nums;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/743925.htmlTechArticleStatic variables only exist within the function scope, and 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. ...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!