【问题标题】:PHP: The use of objects and how to properly use themPHP:对象的使用以及如何正确使用它们
【发布时间】:2016-10-30 17:40:13
【问题描述】:

我一直在处理一个处理对象的 PHP 问题,但到目前为止我遇到了一些麻烦。

要求:

  1. 定义具有受保护属性的车辆类:品牌、型号、年份、价格。创建一个接受品牌、型号、年份和价格的构造方法。实现一个公共方法 displayObject() 来显示每个对象实例的属性。

  2. 定义一个派生类 LandVehicle,它继承自 Vehicle 类并包含一个私有属性:maxSpeed。您可能需要重写此派生类的构造函数和 displayObject() 方法。

  3. 定义另一个派生类 WaterVehicle,它也继承自 Vehicle 类并包含私有属性:boatCapacity。您可能需要重写此派生类的构造函数和 displayObject() 方法。

  4. 实例化(创建)至少三个 LandVehicle 对象并显示每个对象实例的属性。

  5. 实例化(创建)至少三个 WaterVehicle 对象并显示每个对象实例的属性。

我现在的代码:

class Vehicle {

protected int $make;
protected int $model;
protected int $year;
protected int $price;

function_construct() {
    $this->make = "";
    $this->model = "";
    $this->year = "";
    $this->price = "";
}

function_construct($make, $model, $year, $price) {
    $this->make = $make;
    $this->model = $model;
    $this->year = $year;
    $this->price = $price;
}

public function displayObject() {
    return $this->$make . " " . $this->$model . " " . $this->$year . " " . $this->$price; 
}
}

class LandVehicle extends Vehicle {

private int maxSpeed;
protected int $make;
protected int $model;
protected int $year;
protected int $price;
}   

class WaterVehicle extends Vehicle {

private int boatCapacity;
protected int $make;
protected int $model;
protected int $year;
protected int $price;
}

目前,类 (Vehicle) 已使用 4 个变量声明:品牌、型号、年份和价格。我关闭了 displayObject() 方法(除非我做错了什么)。通过继承 Vehicle 类,我能够创建新的派生类:LandVehicle 和 WaterVehicle。这些是容易的部分。困难的部分是如何覆盖派生类的构造函数和 displayObject() 方法?它只是一个回声声明还是还有更多。我应该创建一个 for、while 甚至 foreach 循环吗?

【问题讨论】:

    标签: php inheritance


    【解决方案1】:

    您可以使用parent 关键字调用父方法:

    class Vehicle
    {
      protected $make;
      protected $model;
      protected $year;
      protected $price;
    
      public function __construct($make, $model, $year, $price)
      {
        $this->make = $make;
        $this->model = $model;
        $this->year = $year;
        $this->price = $price;
      }
    
      public function displayObject()
      {
        return $this->make . " " . $this->model . " " . $this->year . " " . $this->price; 
      }
    }
    
    class LandVehicle extends Vehicle
    {
      protected $maxSpeed;
    
      public function __construct($make, $model, $year, $price, $maxSpeed)
      {
        parent::__construct($make, $model, $year, $price);
    
        $this->maxSpeed = $maxSpeed;
      }
    
      public function displayObject()
      {
        return parent::displayObject() . ' ' . $this->maxSpeed; 
      }
    }
    

    对水上交通工具做同样的事情。

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 2020-03-17
      • 1970-01-01
      相关资源
      最近更新 更多