我正在尝试写一个程序,但是我遇到了一些错误。
基础车类
Camaro Car Class
代码情景: 在这个例子中,我需要创建一个Camaro实例并告诉它驱动,我会假设它在一条直线上移动而且没有其他驱动因素。汽车将加速直至达到最大速度。驱动器需要调用加速。需要加速将当前速度增加1.一旦Camaro达到最大速度,它应该停止加速并打印它达到汽车最大速度。然后驱动器的执行也应该停止。*
我的代码低于我试过的。
<?php
class Car extends CI_Controller
{
public function accelerate($_brand,$_max)
{
if($this->$_speed<=$_max)
{
$this->$_speed += 1;
return true;
}
else
{
echo $this->_brand . 'Reached max speed';
}
function drive()
{
$this->accelerate();
}
}
public $_speed = 0;
public $_brand = 'unknown';
public $_max = 0;
}
class Camaro extends Car
{
public $_brand = 'Chevy';
public $_max = 100;
}
$car1 = new Camaro();
echo $car1 -> accelerate($_brand,$_max);
?>
答案 0 :(得分:1)
让我们摆脱代码中的一些小恐怖并重新格式化;)
1)而不是$this->$_speed
使用$this->_speed
2)将所有属性声明放在班级的顶部
class Car extends CI_Controller
{
public $_speed = 0;
public $_brand = 'unknown';
public $_max = 0;
public function accelerate($_brand,$_max)
{
if($this->_speed<=$_max)
{
$this->_speed += 1;
return true;
}
else
{
echo $this->_brand . 'Reached max speed';
}
}
public function drive()
{
$this->accelerate();
}
}
class Camaro extends Car
{
public $_brand = 'Chevy';
public $_max = 100;
}
$car1 = new Camaro();
echo $car1 -> accelerate($car1->_brand, $car1->_max);
?>
答案 1 :(得分:1)
只需编辑下面的代码:
1)在Car class中:
if($this->_speed<=$_max)
{
$this->_speed += 1;
return true;
}
2)演示
$car1 = new Camaro();
echo $car1->accelerate($car1->_brand, $car1->_max);
答案 2 :(得分:0)
我终于得到了解决方案。谢谢您的帮助。这是对我有用的最终计划。
<?php
class Car extends CI_Controller
{
public $_speed = 0;
public $_brand = 'unknown';
public $_max = 0;
public function accelerate($_brand,$_max)
{
for ($_speed = 0; $_speed <= $_max; $_speed++)
{
if ($this->_speed <$_max)
{
echo "<p>$_speed<p>";
}
}
echo $this->_brand . ' reached max speed.';
}
public function drive()
{
$this->accelerate();
}
}
class Camaro extends Car
{
public $_brand = 'Chevy';
public $_max = 100;
}
$car1 = new Camaro();
echo $car1 -> accelerate($car1->_brand, $car1->_max);
?>
//output 1 2 3 ... 100 Chevy reached max speed.