如何覆盖PHP类的构造函数?

时间:2017-09-14 19:33:49

标签: php oop

这是我的代码。我没有经验,所以请用简单的语言告诉我答案。

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

println是必要的回声,但在消息之前有一个\ 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中Car的消息,因此__construct()没有改变。

2 个答案:

答案 0 :(得分:4)

你的问题在这一行:

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

您从未尝试过创建ElectricCar。将该行更改为

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

并且一切都应该按预期工作。

答案 1 :(得分:2)

实际上,您已经覆盖了父构造函数,只是在子类中编写了一个新的构造函数。如果不重写构造函数,则会调用父构造函数。

从您的代码中我可以看到您将Tesla创建为Car而不是ElectricCar,这就是您收到Car消息而不是ElectricCar消息的原因。

FYI当您希望子类构造函数扩展父类构造函数时,您需要做的就是以这种方式调用父构造函数

parent::__construct();