问题
I am trying to write to write a program, but am getting some errors.
Base Car Class
- current speed (property) – default value 0
- accelerate (method)
- drive (method)
- brand (property) - default value ‘unknown’
- max speed (property) - default value 0
Camaro Car Class
- Inherits Base Car
- brand (property) - default value ‘Chevy’
- max speed (property) – default value 200
Code Scenario: In this example I need to create an instance of Camaro and tell it to drive, I will assume it’s moving in a straight line and there are no other driving factors. The car will accelerate until it hits its max speed. It is required that drive will call accelerate. It is required accelerate will increment the current speed by 1. Once the Camaro reaches max speed it should stop accelerating and print that it hit the cars max speed. The execution of drive should then also stop.*
My Code is below which I tried.
<?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);
?>
回答1:
Lets get rid of some little horrors in the code and reformat it ;)
1) instead of $this->$_speed use $this->_speed
2) put all property declarations at the top of your class
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);
?>
回答2:
Just edit the code bellow:
1) in Car class:
if($this->_speed<=$_max)
{
$this->_speed += 1;
return true;
}
2) Demo
$car1 = new Camaro();
echo $car1->accelerate($car1->_brand, $car1->_max);
回答3:
I finally got the solution. Thanks for the help. This is the final program which worked for me.
<?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.
来源:https://stackoverflow.com/questions/34360564/undefined-variable-in-program