靜態(tài)屬性、方法(包括靜態(tài)與非靜態(tài))在內存中,只有一個位置(而非靜態(tài)屬性,有多少實例化對象,就有多少個屬性)。
(推薦教程:php圖文教程)
實例:
header("content-type:text/html;charset=utf-8"); class Human{ static public $name = "小妹"; public $height = 180; static public function tell(){ echo self::$name;//靜態(tài)方法調用靜態(tài)屬性,使用self關鍵詞 //echo $this->height;//錯。靜態(tài)方法不能調用非靜態(tài)屬性 //因為 $this代表實例化對象,而這里是類,不知道 $this 代表哪個對象 } public function say(){ echo self::$name . "我說話了"; //普通方法調用靜態(tài)屬性,同樣使用self關鍵詞 echo $this->height; } } $p1 = new Human(); $p1->say(); $p1->tell();//對象可以訪問靜態(tài)方法 echo $p1::$name;//對象訪問靜態(tài)屬性。不能這么訪問$p1->name //因為靜態(tài)屬性的內存位置不在對象里 Human::say();//錯。say()方法有$this時出錯;沒有$this時能出結果 //但php5.4以上會提示 ?>
(視頻教程推薦:php視頻教程)
總結:
(1)靜態(tài)屬性不需要實例化即可調用。因為靜態(tài)屬性存放的位置是在類里,調用方法為"類名::屬性名";
(2)靜態(tài)方法不需要實例化即可調用。同上
(3)靜態(tài)方法不能調用非靜態(tài)屬性。因為非靜態(tài)屬性需要實例化后,存放在對象里;
(4)靜態(tài)方法可以調用非靜態(tài)方法,使用 self 關鍵詞。php里,一個方法被self:: 后,它就自動轉變?yōu)殪o態(tài)方法;