課程
/后端開發
/PHP
/PHP進階篇
speedup 方法里面為啥不用return speed 下面可以直接用echo $car->speed打印出來?????
2016-03-17
源自:PHP進階篇 2-4
正在回答
這個是可以的,你需要根據需要來決定是否使用 return。按照你說的應該是使用 return $this->speed,而不是使用 return speed。你寫的有兩個錯誤,首先變量要使用?$?符號調用。其次在類中的函數中不能直接使用 $speed 調用類實例的局部變量,你如果在函數中直接 return $speed 那么這個 $speed 變量是屬于這個函數的局部變量而不是類實例中聲明的 $speed 變量,你不賦值直接輸出這個 $speed 會顯示這是一個未定義的變量。
正解:
class Car {
? ? public $speed = 0;
? ? public function speedUp() {
? ? ? ? $this->speed += 10;
? ? ? ? return $this->speed;
? ? }
}
$car = new Car();
echo $car->speedUp();
錯誤:return speed、return $speed
舉報
輕松學習PHP中級課程,進行全面了解,用PHP快速開發網站程序
3 回答為什么是return $this->name; 而不是return $this->$name;
2 回答為什么return的方法不行
1 回答return是干什么用的
2 回答speedUp方法里面為什么要用return self::$speed+=10;
1 回答覆蓋了speedUp,為什么不重寫return呢
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2016-03-17
這個是可以的,你需要根據需要來決定是否使用 return。按照你說的應該是使用 return $this->speed,而不是使用 return speed。你寫的有兩個錯誤,首先變量要使用?$?符號調用。其次在類中的函數中不能直接使用 $speed 調用類實例的局部變量,你如果在函數中直接 return $speed 那么這個 $speed 變量是屬于這個函數的局部變量而不是類實例中聲明的 $speed 變量,你不賦值直接輸出這個 $speed 會顯示這是一個未定義的變量。
正解:
class Car {
? ? public $speed = 0;
? ? public function speedUp() {
? ? ? ? $this->speed += 10;
? ? ? ? return $this->speed;
? ? }
}
$car = new Car();
echo $car->speedUp();
錯誤:return speed、return $speed