<?php
//定义一个全局变量,用来保存总共的人数
global $global_nums;
class Child{
public $name;
//该类的构造方法
public function __construct($name){
$this->name=$name;
}
//计算总共人数的方法
public function join_game(){
global $global_nums;
$global_nums+=1;
echo $this->name."加入游戏<br/>";
}
}
$child1=new Child("张飞");
$child1->join_game();
$child2=new Child("李逵");
$child2->join_game();
$child3=new Child("猪八戒");
$child3->join_game();
echo "<br/>共有".$global_nums;
?>
全局变量:
<?php
class Child{
//成员变量
public $name;#名字
public static $nums;#所有的人数
//构造方法
public function __construct($name){
$this->name=$name;
}
//计算总共人数的方法
public function join_game(){
//静态变量在类内部的访问的方式
self::$nums+=1;
echo $this->name."加入游戏<br/>";
}
}
//创建对象实例
$child1=new Child("孙悟空");
//调用join_game()方法
$child1->join_game();
//创建对象实例
$child2=new Child("葫芦娃");
//调用join_game()方法
$child2->join_game();
//输出总共的人数===》Child::$nums静态变量在类的内部或者是外部的访问方式
echo "<br/>总共的人数为:".Child::$nums;
?>
什么时候使用静态变量:
当变量需要对所有的对象共享操作的时候,就需要使用静态变量,如一个班里的所有的学生交学费,所以要定义一个静态的变量,来保存总共的学费的数目是多少。