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