php - 警告:第 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、会话等,但它仍然不起作用。可能是什么错误?
解决方案
您不小心将最后两个函数移到了课堂之外。因此,您的类在没有其构造函数的情况下被构造。
} // <--- 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;
}
显然,如果您朋友的代码有效而您的代码无效,那么它们一定不一样。您应该考虑与您的朋友共享此项目的代码存储库。使用版本控制,这种类型的差异会很明显,而且学习起来也可能很有趣。
如果不是因为那个错误,看起来除以零错误是不可能的,除非你建造了一辆零燃料容量的汽车。
推荐阅读
- java - 无法更新eclipse出现错误
- flutter - pageview.builder ,当我点击选项时没有错误但页面没有改变
- python - 在 AWS lambda 函数中使用来自 S3 存储桶的 Pandas read_csv 时出错 - 第 5 行中预期有 1 个字段,看到 2
- java - 在验证中检查多个条件
- r - 如何将多个excel工作簿合并到数据框中使用R中新ID列中的特定单元格
- java - Micronaut:如何用@Context替换@EventListener与@Singleton结合?
- c++ - 如何在 vscode 中的 powershell 上运行命令?
- javascript - React,使用 useEffect 更新数据,一个数据是一个数组,但是当我使用 map 或 Object.keys(data).map 时,两者都不起作用。如何让它发挥作用?
- http - golang 正确的 http2 请求
- django - 如何在 Django 模型的 ManyToManyField 中添加 id(而不是对象)?