可以';我不明白为什么变量不是';t更新


Can't figure out why variable isn't updating

我下面有一个小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>

问题在于您的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;