我一直在研究处理对象的PHP问题,但到目前为止我遇到了一些麻烦。
要求:
定义一个具有受保护属性的类:制造商,型号,年份,价格。创建一个接受make,model,year和price的构造函数方法。实现一个公共方法displayObject()来显示每个对象实例的属性。
定义一个派生类LandVehicle,它继承自Vehicle类并包含一个私有属性:maxSpeed。您可能需要覆盖此派生类的构造函数和displayObject()方法。
定义另一个派生类WaterVehicle,它也继承自Vehicle类并包含私有属性:boatCapacity。您可能需要覆盖此派生类的构造函数和displayObject()方法。
实例化(创建)LandVehicle的至少三个对象并显示每个对象实例的属性。
实例化(创建)至少三个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;
}
目前,已经使用4个变量声明了类(Vehicle):make,model,year和price。我将displayObject()方法关闭(除非我做错了)。我能够通过继承Vehicle类来创建新的派生类:LandVehicle和WaterVehicle。那些是容易的部分。困难的部分是如何覆盖派生类的构造函数和displayObject()方法?它只是一个回声声明还是还有更多。我应该创建for,while,甚至foreach循环吗?
答案 0 :(得分:0)
您可以使用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;
}
}
为水上运输工具做同样的事情。