類當(dāng)中的this是怎么使用的??
class Car {
? ? private $speed = 0;
? ??
? ? public function getSpeed() {
? ? ? ? return $this->speed;
? ? }
? ??
? ? protected function speedUp() {
? ? ? ? $this->speed += 10;
? ? }
? ??
? ? //增加start方法,使他能夠調(diào)用受保護(hù)的方法speedUp實現(xiàn)加速10
public static function start(){
? ? $this->speedUp();
}
}
$car = new Car();//為什么這里會報錯
Car::start();
echo $car->getSpeed();
2017-01-05
$this 為class(類) 實例化后的對象,所以使用靜態(tài)方法Car::start()調(diào)用start()時,start()函數(shù)里面使用的是$this->speedUp(),是無法調(diào)用speedUp()(受保護(hù)的方法),所以需要改為self::speedUp()。但這個時候,你仍然發(fā)現(xiàn)還是會報錯,是因為speedUp()方法當(dāng)中調(diào)用了非靜態(tài)屬性$speed,在PHP當(dāng)中是不能靜態(tài)調(diào)用非靜態(tài)屬性的。