程序

时间:2015-12-18 17:06:59

标签: php inheritance

我正在尝试写一个程序,但是我遇到了一些错误。

基础车类

  1. 当前速度(属性) - 默认值0
  2. 加速(方法)
  3. 驱动器(方法)
  4. 品牌(财产) - 默认值'未知'
  5. 最大速度(属性) - 默认值0
  6. Camaro Car Class

    1. 继承基地车
    2. 品牌(财产) - 默认值'雪佛兰'
    3. 最大速度(属性) - 默认值200
    4. 代码情景: 在这个例子中,我需要创建一个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);
      ?>
      

3 个答案:

答案 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.