2017-09-14 73 views
0

這是我的代碼。我沒有經驗,所以請用簡單的語言告訴我答案。如何覆蓋PHP類的構造函數?

<?php 
function println($message) { 
    echo "\n".$message; 
} 

println是essentialy回聲,但與消息之前的\ n。我只是習慣於Python 3,但不能使用print()。

class Car { 
    public function __construct($name) { 
    //If the constructor is that of a car, it will be said that a car was made. 

     println("Car made!"); 
     $this->distance_drived = 0; 
     $this->name = $name; 
    } 
    function introductory() { 
     return "This car is called ".$this->name."."; 
    } 
} 

class Battery { 
    function __construct($max_capacity, $current_capacity) { 
     echo "Constructed!"; 
     $this->max_capacity = $max_capacity; 
     $this->current_capacity = $current_capacity; 
    } 
    function fill($amount) { 
     if ($amount + $this->current_capacity >= $this->max_capacity) { 
      $this->fill_full(); 
     } else { 
      $this->current_capacity += $amount; 
     } 
    } 
    function fill_full() { 
     $this->current_capacity = $this->max_capacity; 
    } 
    function use_power($amount) { 
     if ($amount + $this->current_capacity >= $this->max_capacity) { 
      return $this->current_capacity; 
      $this->current_capacity = 0; 
     } else { 
      $this->current_capacity -= $amount; 
      return $amount; 
     } 
    } 
    function check_percentage() { 
     return ($this->current_capacity/$this->max_capacity) * 100; 
    } 
} 

class ElectricCar extends Car { 
    public function __construct($name, $max_capacity, $current_capacity, $power_per_km) { 
     println("Electric car made!"); 

     //If the constructor is that of an electric car, it will be said that a car was made. 

     $this->distance_drived = 0; 
     $this->name = $name; 
     println($max_capacity); 
     $this->battery = new Battery($max_capacity, $current_capacity); 
    } 
    public function move($km) { 
     $power_required = $km * $this->power_per_km; 
     $used = $battery->use_power($power_required); 
     $this->distance_drived += $used/$this->power_per_km; 
    } 
} 

$toyota = new Car("Toyota 2017"); 
println($toyota->name); 
println($toyota->introductory()); 
$tesla = new Car("Tesla Model S", 1000, 750, 5); 
println($tesla->introductory()); 
println("Capacity is ".$tesla->battery->max_capacity); 

?> 

我的主要問題是,該消息仍然是汽車的在ElectricCar消息,所以__construct()並沒有改變。

+0

嘗試'$特斯拉=新ElectricCar(「特斯拉S型「,1000,750,5);'那麼至少你會使用正確的類來實例化'$ tesla'對象 – RiggsFolly

+0

我建議我們把它作爲TYPO來關閉 – RiggsFolly

回答

4

您的問題是在這條線:

$tesla = new Car("Tesla Model S", 1000, 750, 5); 

你從來沒有試圖創造一個ElectricCar。將該行更改爲

$tesla = new ElectricCar("Tesla Model S", 1000, 750, 5); 

並且所有內容都應按預期工作。

1

其實你已經覆蓋父構造函數,只是在子類中寫一個新的構造函數。當你不重寫構造函數時,則調用父函數。

從您的代碼中,我可以看到您將Tesla創建爲Car,而不是ElectricCar,這就是您獲取Car消息而不是ElectricCar消息的原因。

FYI當你希望你的孩子類的構造函數來擴展父類的構造函數,你所要做的是調用父類的構造這樣

parent::__construct();