chris
chris

Reputation: 21

Can't figure out why variable isn't updating

I have a small PHP program below that is supposed to calculate the fuel, miles, etc of a Car object. I am getting good output, with the exception of the "miles" part. It is overwriting the original so that I get total per segment instead of total miles.

I'm a newbie, so I am sure this is simple. Thanks in advance.

   <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>

Upvotes: 0

Views: 80

Answers (1)

T3 H40
T3 H40

Reputation: 2426

The problem is your if statement:

if ($miles < ($this->fuel * $this->mpg)){
    $this->miles = $miles;
} else {
    $this->miles = ($this->fuel * $this->mpg);
}  

by calling $this->miles = $miles; you overwrite its current value.

You can use the += operator to add to its value instead: $this->miles += $miles;

Don't forget to then reduce your fuel by ($this->fuel) - ($miles / $this->mpg); instead, so you don' t use your total miles count.

You can apply this technique to other statements as well, e.g. $this->fuel = $this->fuel + $gallons; becomes $this->fuel += $gallons;

Upvotes: 1

Related Questions