我有一个小的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>
答案 0 :(得分:1)
问题是你的if
声明:
if ($miles < ($this->fuel * $this->mpg)){
$this->miles = $miles;
} else {
$this->miles = ($this->fuel * $this->mpg);
}
通过调用$this->miles = $miles;
覆盖其当前值。
您可以使用+=
运算符来添加其值:$this->miles += $miles;
请不要忘记将燃油减少($this->fuel) - ($miles / $this->mpg);
,以免造成总里程数。
您也可以将此技术应用于其他语句,例如$this->fuel = $this->fuel + $gallons;
变为$this->fuel += $gallons;