为什么子类没有调用父类的构造函数


Why is child class not calling constructor of parent class?

来自php.net

如果子类没有定义构造函数,那么它可能会像普通类方法一样从父类继承(如果它没有声明为私有)。

据我所知,如果我不在子对象中定义构造函数,则会调用父对象的构造函数。

例如,我制作了一个带有构造函数的父类。实例化了子类和父类,但是它抛出以下警告:警告:缺少车辆的参数1:__construct()

示例代码:

class vehicle{
    protected $type;
    function __construct($type){
        $this->type = $type;
        echo "Type chosen: $this->type";
    }
}
class car extends vehicle{
}
$vehicle = new vehicle("sport");
$car = new car;

好吧,它正在调用父类的构造函数。由于您没有为构造函数提供任何参数,所以当您声明$car对象时,它会警告您缺少参数。

您应该通过提供"type"参数来初始化子类对象,如下所示:

$car = new car("family");