標籤:des style blog http color io os 使用 ar
php全域變數使用關鍵字global聲明,靜態變數使用static聲明,靜態變數的使用可以使用 類名::變數名
範例程式碼:
1 <?php 2 3 //全域變數global 的用法和靜態變數的使用 4 global $sum; 5 $sum=0; 6 class Person 7 { 8 public $name; 9 public $age;10 public static $zong=0;11 public function __construct($name,$age)12 {13 $this->name=$name;14 $this->age=$age;15 }16 public function addnew()17 {18 echo $this->name."加入團隊!<br/>";19 global $sum;20 $sum++;21 self::$zong++;22 }23 public function __destruct()24 {25 echo "<br/>".$this->name."離開團隊!<br/>";26 }27 }28 $p1=new Person("張三",12);29 $p1->addnew();30 $p2=new Person("李四",13);31 $p2->addnew();32 echo "共有".$sum."人加入團隊<br/>";33 echo "<br/><br/><br/><br/>";34 echo "靜態變數的記錄值為".Person::$zong;35 36 //靜態變數global的用法37 38 ?>View Code
靜態方法的使用樣本:
1 <?php 2 class Student 3 { 4 public static $sum=0; 5 public $fee; 6 public $name; 7 public function __construct($name,$fee) 8 { 9 echo $name."加入學校,花費".$fee."元<br/>";10 $this->$fee=$fee;11 $this->$name=$name;12 self::$sum+=$fee;13 }14 public static function getFee()15 {16 return self::$sum;17 }18 }19 $st1=new Student("張三",12);20 $st2=new Student("李四",13);21 echo "學校共收入(類名靜態方法調用)".Student::getFee()."元<br/>";22 echo "學校共收入(執行個體靜態方法調用)".$st1->getFee()."元<br/>";23 ?>View Code
【php全域變數和靜態變數、靜態方法的使用方法】