靜態成員屬於類別本身,為所有實例共享。靜態變數稱「類別變數」,靜態方法稱「類別方法」。
class Child {
public static $nums = 0; // 定義
public function join_game() { self::$nums++; } // 類別內部存取
}
echo Child::$nums; // 類別外部存取
| 特性 | 靜態變數 | 實例變數 |
|---|---|---|
| 關鍵字 | static | 無 |
| 所屬 | 類別 | 物件實例 |
| 存取方式 | 類別名::變數名 | $obj->變數名 |
| 共享性 | 所有實例共享 | 各實例獨立 |
<?php
class Child {
public $name; public static $nums = 0;
function __construct($name){ $this->name=$name; }
public function join_game(){ self::$nums++; echo $this->name."加入遊戲<br/>"; }
}
$c1=new Child("www.bianceng.cn"); $c1->join_game();
$c2=new Child("李四"); $c2->join_game();
$c3=new Child("王二"); $c3->join_game();
echo "共有 ".Child::$nums." 人玩遊戲";
?>
class Student {
public static $fee = 0;
public static function enterSchool($ifee){ self::$fee += $ifee; }
public static function getFee(){ return self::$fee; }
}
Student::enterSchool(340); // 類別名呼叫
$stu = new Student(); $stu->enterSchool(600); // 物件也可呼叫
echo Student::getFee();
$this 不可用)。