class School
{
static public $name = '中學';
public $address = '北京';
public $studentNum;
public function __construct(){
$this->studentNum = 1000;
echo __LINE__;
}
static public function getCurrentName(){
echo self::$name;//靜態方法調用靜態屬性,使用self關鍵詞
//echo $this->address;//錯,靜態方法不能調用非靜態屬性
//因爲,$this代表實例化對象,而這裏是類,不知道$this代表那個對象
}
public function getStudentNum(){
echo self::$name;//普通方法調用靜態屬性,同樣使用self關鍵詞
echo $this->studentNum;
}
}
$s1 = new School();
$s1->getStudentNum();
$s1->getCurrentName();//對象可以訪問靜態方法
echo $s1::$name;//對象訪問靜態屬性。不能這麼訪問$s1->name,因爲靜態屬性的內存位置不在對象裏面
School::getStudentNum();//錯,getStudent方法有$this時出錯,沒有$this時能出結果
//調用類的靜態函數是不會自動調用類的構造函數,只有實例化對象是時纔會觸發構造函數
School::getCurrentName();
總結
1、靜態屬性不需要實例化即可調用,因爲靜態屬性存放的位置是類裏,調用方法爲"類名::屬性"
2、靜態方法不能調用非靜態屬性。因爲非靜態屬性需要實例化後,存放在對象裏;
3、靜態方法可以調用非靜態方法,使用關鍵詞。php裏,一個方法被self::後,它就自動轉變爲靜態方法
4、調用類的靜態函數是不會自動調用類的構造函數。