2016-10-30 33 views
1

我一直在處理一個處理對象的PHP問題,但到目前爲止我有點麻煩。PHP:使用對象以及如何正確使用它們

的要求:

  1. 定義一個類車輛已保護的性質:製造商,型號,年份,價格。創建一個構造函數方法,其中包含make,model,year和price。實現公共方法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; 
} 

目前,該班(車)已宣佈與4個變量:製造商,型號,年份和價格。我有displayObject()方法關閉(除非如果我做錯了什麼)。通過繼承Vehicle類,我能夠創建新的派生類:LandVehicle和WaterVehicle。那些是簡單的部分。難的部分是你如何重寫派生類的構造函數和displayObject()方法?這僅僅是一個回聲陳述,還是更多呢?我應該創建一個for,while,還是foreach循環?

回答

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; 
    } 
} 

執行相同的水車輛。

相關問題