2016-10-30 5 views
1

객체를 다루는 PHP 문제를 해결하고 있지만 지금까지는 약간 문제가 있습니다.PHP : 객체의 사용법과 객체를 올바르게 사용하는 방법

요구 사항 :, 모델, 연식, 가격을 :

  1. 속성을 보호 한 클래스 차량을 정의합니다. make, model, year 및 price를 취하는 생성자 메서드를 만듭니다. public 메서드 displayObject()를 구현하여 각 객체 인스턴스의 속성을 표시합니다.

  2. Vehicle 클래스에서 상속 받고 private 속성 인 maxSpeed가 포함 된 파생 클래스 LandVehicle을 정의합니다. 이 파생 클래스에 대해 constructor 및 displayObject() 메서드를 재정의해야 할 수 있습니다.

  3. Vehicle 클래스에서 상속 받고 private 속성 인 boatCapacity가 포함 된 다른 파생 클래스 WaterVehicle을 정의합니다. 이 파생 클래스에 대해 constructor 및 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; 
    } 
} 

물 차량에 대해 동일한 작업을 수행합니다.

관련 문제