對象 OOP
1.Fatal error: Using $this when not in object context
這個錯誤剛學 OOP 肯定容易出現,因為有個概念你沒有真正理解。 類的可訪問性(accessible),也可以說是作用域, 你還可以認為是 1個 中國人 在國外,他不屬於哪個文化,他不講外語(可能他知道點);但是他無法通過自己跟老外溝通,因為他們不是在一個共同國度出生。
那么錯誤是如何發生的呢?看下面的例子:
1 <?php 2 class Trones{ 3 static public $fire = "I am fire."; 4 public $water = "I am water"; 5 6 static function getFire( ) { 7 return $this->fire ; // wrong 8 } 9 static function getWater( ) { 10 return $self::water ; // wrong 11 } 12 13 static function Fire( ) { 14 return self::$fire ; // be sure you use self to access the static property before you invoke the function 15 } 16 } 17 18 /* 19 Fatal error: Using $this when not in object context 20 */ 21 //echo Trones::getFire( ) ; 22 //echo Trones::getWater( ) ; 23 24 // correct 25 echo Trones::Fire( ); 26 echo "<br />" ; 27 $trones = new Trones ; 28 $trones->fire ; // Notice: Undefined property: Trones::$fire (base on defferent error setting) simple is error 29 echo Trones::$fire ;
這個錯誤很經典, 也很實用,先看 static 的定義:
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
翻譯:定義一個類的屬性或方法為靜態時,可以使他們在不需要初始化一個類時就能直接訪問 。一個被定義為了靜態的屬性不能被類的對象用對象操作符訪問* -> *,(可以通過靜態的方法訪問)。
例子說明:
7行 10行 犯了同一個錯誤,第一個是用對象操作符來訪問靜態變量。你看看定義,$this 是一個偽變量 相當於 object,一個實例。你用對象操作符 -> 訪問就會報錯。
同樣你也不能用 靜態操作符 :: 來訪問一個公共變量 。 正確的訪問應該是 14行 25行,一個是在類的定義里訪問(self:: === Trones::),一個是在類的外部訪問。
對於繼承類,以上的規則同樣適合。
------------------------------------------------------ 分割線--------------------------------------------------------------------------------------
2.Fatal error: Call to private method
最近有部連續劇很好看,叫權利的游戲,我們假設有 3方人馬, 7個國王, 平民, 龍女。 他們三方人馬在下面爭奪最終的勝利, 也就是王冠。
下面的故事還有一個標題:類的可見性(visibility) 你如果知道最終的答案,解釋部分你可以略過了。
1 <?php 2 3 class Trones { 4 protected $fire = " fire "; 5 public $water = " water " ; 6 static private $trones = "Trones"; 7 8 protected function getFire( ) { 9 $this->fire ; 10 } 11 12 static public function TheDragenOfMather( ) { 13 return __METHOD__." use ".$this->getFire()." gets the ".self::getTrones( ) ; 14 } 15 16 static public function getWater( ) { 17 return __METHOD__ ; 18 } 19 20 static private function getTrones( ) { 21 return self::$trones ; 22 } 23 24 } 25 26 class Kings extends Trones { 27 static function TheSevenKing( ) { 28 return __METHOD__."gets the ".self::getTrones( ); 29 } 30 } 31 32 class People extends Trones{ 33 static function ThePeople( ) { 34 return __METHOD__."gets the ".self::getTrones( ); 35 } 36 } 37 echo Kings::TheSevenKing( ) ; 38 echo Trones::TheDragenOfMather( ) ; 39 echo People::ThePeople( ) ;
正確答案是:7國征戰 內斗,平民死傷無數,龍女想乘機漁翁得利;可惜 最終誰也沒有得到皇冠和勝利。哈哈。
當static 碰到 private ,結合產生復雜,也產生美;就像抽象的人,像我們大學老師講的數學課;(不過網易的公開數學課很好)
如果想要龍女 獲得最后的勝利, 你只要幫她一把 將13行的 $this->getFire() 這部分去掉就可以了。同樣的道理 你無法在一個靜態函數里 使用任何對象操作符。
怎么使人民獲得王冠呢? 你去奮斗吧!
如果你不構建大型的框架和網站 這些概念比如 Interface Implement abstract 。。。 你還是不知道的好。