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