靜態(tài)屬性、方法(包括靜態(tài)與非靜態(tài))在內(nèi)存中,只有一個(gè)位置(而非靜態(tài)屬性,有多少實(shí)例化對(duì)象,就有多少個(gè)屬性)。
(推薦教程:php圖文教程)
實(shí)例:
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)方法調(diào)用靜態(tài)屬性,使用self關(guān)鍵詞 //echo $this->height;//錯(cuò)。靜態(tài)方法不能調(diào)用非靜態(tài)屬性 //因?yàn)?$this代表實(shí)例化對(duì)象,而這里是類,不知道 $this 代表哪個(gè)對(duì)象 } public function say(){ echo self::$name . "我說話了"; //普通方法調(diào)用靜態(tài)屬性,同樣使用self關(guān)鍵詞 echo $this->height; } } $p1 = new Human(); $p1->say(); $p1->tell();//對(duì)象可以訪問靜態(tài)方法 echo $p1::$name;//對(duì)象訪問靜態(tài)屬性。不能這么訪問$p1->name //因?yàn)殪o態(tài)屬性的內(nèi)存位置不在對(duì)象里 Human::say();//錯(cuò)。say()方法有$this時(shí)出錯(cuò);沒有$this時(shí)能出結(jié)果 //但php5.4以上會(huì)提示 ?>
(視頻教程推薦:php視頻教程)
總結(jié):
(1)靜態(tài)屬性不需要實(shí)例化即可調(diào)用。因?yàn)殪o態(tài)屬性存放的位置是在類里,調(diào)用方法為"類名::屬性名";
(2)靜態(tài)方法不需要實(shí)例化即可調(diào)用。同上
(3)靜態(tài)方法不能調(diào)用非靜態(tài)屬性。因?yàn)榉庆o態(tài)屬性需要實(shí)例化后,存放在對(duì)象里;
(4)靜態(tài)方法可以調(diào)用非靜態(tài)方法,使用 self 關(guān)鍵詞。php里,一個(gè)方法被self:: 后,它就自動(dòng)轉(zhuǎn)變?yōu)殪o態(tài)方法;