在我们的很多时候,可能会用到静态变量,如统计随时可变的量,尽管也可以使用global(全局变量),但是这样容易破坏类的结构性,所以,使用静态变量来表示或则控制可变的量,也可以理解为共享的量,下面是我对静态变量取出的的两种方式特点认识:
1:首先,经过测试,静态变量是可以脱离对象而存在的,准确的说,静态变量是属于类的。
2:在类内有self和对象取值两种方式,在类外,只有对象取值这一种方式。
3:普通函数函数可以操作静态变量,反过来静态函数就不能操作普通变量
下面是我的测验过程代码:
全局变量的使用:
global $StudentNum;
$StudentNum = 0;
class Student{
public function __construct($name){
$this->name1 = $name;
//这里说明的是类内元素和参数的比较
global $StudentNum;
$StudentNum++;
echo "第".$StudentNum."个学生--".$this->name1."--加入游戏"."<br/>";
}
}
$student_1 = new Student("小黑");
$student_2 = new Student("小白");
$student_3 = new Student("小李");
$student_4 = new Student("小张");
$student_5 = new Student("小黄");
$student_6 = new Student("小灰");
?>
静态变量的使用
<?php
class Student{
/*public $name;*/
//静态变量是共享的变量
static public $StudentNum=0;
public function __construct($name){
/*$this->name=$name;*/
self::$StudentNum++.'<br/>';
echo "第".Student::$StudentNum."个学生".$name."参加游戏".'<br/>';
}
//下面的因为没执行所以才会没显示错误
public function ShowStudent(){
$this->StudentNum = "999";
}
}
//静态变量并不依赖对象而存在
/*$student_1 = new Student;
$student_1->StudentNum;
echo Student::$StudentNum;
/*$student_1 = new Student("hu");
$student_1 = new Student("hu");
$student_1 = new Student("hu");
$student_1 = new Student("hu");*/
echo Student::$StudentNum;//在类的外面只有这一种方法进行访问
?>