PHP的基本常识(2)
对象 OOP1.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 function15 }16 }17 18 /*19 Fatal error: Using $this when not in object context20 */21 //echo Trones::getFire( ) ;22 //echo Trones::getWater( ) ;23 24 // correct25 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 error29 echo Trones::$fire ;
页:
[1]