2015-10-29 61 views
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> 
+0

你覆蓋你的價值:'$這個 - >英里= $英里;'使用'+ ='相反,如果你想存儲總量。 –

+0

你不應該增加里程,而是分配新的值? '$ this-> miles ='表示里程被覆蓋。你應該加入它。 –

+0

'$ this-> miles + = $ miles;' –

回答

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;