为什么子 class 不调用父 class 的构造函数?

Why is child class not calling constructor of parent class?

来自 php.net

If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

据我了解,如果我不在子项中定义构造函数,将调用父项的构造函数。

例如,我用构造函数创建了一个父对象 class。实例化了子项和父项 class,但是它会抛出以下警告: 警告:vehicle::__construct()

缺少参数 1

示例代码:

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;

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

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

$car = new car("family");