首页 > 解决方案 > 警告:第 25 行 C:\xampp\htdocs\practice\VIDEO8\car2\Car.php 中除以零

问题描述

我和朋友一起写了下面的代码。在他的电脑上可以,在我的电脑上不行。代码似乎 100% 相同。任何想法为什么它不起作用?我收到一个错误:

警告:在第 25 行的 xxxxx/Car.php 中除以零。

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

可能是什么问题?在我创建__construct函数之前,一切正常。我删除了所有的 cookie、会话等,但它仍然不起作用。可能是什么错误?

标签: php

解决方案


您不小心将最后两个函数移到了课堂之外。因此,您的类在没有其构造函数的情况下被构造。

} //  <--- your class ends here
    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;

    }

显然,如果您朋友的代码有效而您的代码无效,那么它们一定不一样。您应该考虑与您的朋友共享此项目的代码存储库。使用版本控制,这种类型的差异会很明显,而且学习起来也可能很有趣。

如果不是因为那个错误,看起来除以零错误是不可能的,除非你建造了一辆零燃料容量的汽车。


推荐阅读