I wrote the below code together with a friend. On his computer it worked, on mine it did not. The code seems to be 100% the same. Any ideas why it does not work? I get an error:
Warning: Division by zero in xxxxx/Car.php on line 25.
<?php
class Car{
private $total_fuel;
private $curr_fuel;
private $consumption;
function fill($quantity){
$this->curr_fuel += $quantity;
}
function go($distance) {
$needed = $this->consumption/100 * $distance;
if($this->curr_fuel > $needed){
$this->curr_fuel -= $needed;
}else{
return "Not enough gas for $distance km!". "<br>";
}
}
function fuel_left() {
return $this->curr_fuel *100 / $this->total_fuel;
}
}
function odometer(){
return $this->km;
}
function __construct($total_fuel,$curr_fuel,$consumption) {
$this->total_fuel = $total_fuel;
$this->curr_fuel = $curr_fuel;
$this->consumption = $consumption;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form method="post">
How many km do you want to drive?
<input type="text" name="distance">
<input type="submit" value="Go">
</form>
<?php
session_start();
if(!isset($_SESSION['car'])){
$car = new Car(50,25,10);
}else{
$car = $_SESSION['car'];
}
if(isset($_POST['distance'])){
echo $car->go($_POST['distance']);
echo "Left fuel: {$car->fuel_left()} % <br>";
$_SESSION['car'] = $car;
}
?>
</body>
</html>
What could possibly be the issue? Before I create the __construct
function everything works fine. I deleted all the cookies, sessions etc, but it still does not work. What could possibly be the mistake?