0
我有一個小的PHP程序,它應該是計算Car對象的燃料,英里等。除了「英里數」部分外,我的輸出效果很好。它會覆蓋原始文件,以便每個段獲得總計而不是總里程。找不到爲什麼變量沒有更新
我是個新手,所以我敢肯定這是簡單的。提前致謝。
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
class Car{
private $fuel = 0;
private $mpg = 0;
private $miles = 0;
private $spentGas = 0;
public function __construct($initialGas, $mpg){
$this->fuel = $initialGas;
$this->mpg = $mpg;
}
public function drive($miles){
if ($miles < ($this->fuel * $this->mpg)){
$this->miles = $miles;
} else {
$this->miles = ($this->fuel * $this->mpg);
}
$this->fuel = ($this->fuel) - ($this->miles/$this->mpg);
($this->miles/$this->mpg)*($this->mpg);
}
public function addGas($gallons){
$this->fuel = $this->fuel + $gallons;
}
public function readFuelGauge(){
$this->fuel = $this->fuel - $this->spentGas;
if (($this->fuel)> 0){
return $this->fuel;
} else {
return 0;
}
}
public function readOdometer(){
return $this->miles;
}
public function __toString() {
return 'Car (gas: ' . $this->readFuelGauge() .
', miles: ' . $this->readOdometer() . ')';
}
}
$Car = new Car(20, 25);
$Car -> drive(25);
print($Car . '<br />');
$Car -> drive(1000);
print($Car . '<br />');
$Car -> addGas(5);
$Car -> drive(10);
print($Car . '<p><hr>');
echo '<p>';
var_dump($Car);
?>
</body>
</html>
你覆蓋你的價值:'$這個 - >英里= $英里;'使用'+ ='相反,如果你想存儲總量。 –
你不應該增加里程,而是分配新的值? '$ this-> miles ='表示里程被覆蓋。你應該加入它。 –
'$ this-> miles + = $ miles;' –