gpt4 book ai didi

php - 实例化派生类时是否不隐式调用抽象类构造函数?

转载 作者:IT老高 更新时间:2023-10-28 12:03:56 24 4
gpt4 key购买 nike

举个例子:

abstract class Base {
function __construct() {
echo 'Base __construct<br/>';
}
}

class Child extends Base {
function __construct() {
echo 'Child __construct<br/>';
}
}

$c = new Child();

来自 C# 背景,我希望输出是

Base __construct
Child __construct

但是,实际输出只是

Child __construct

最佳答案

不,如果子类定义了构造函数,则不调用父类的构造函数。

从你的子类的构造函数中,你必须调用父类的构造函数:

parent::__construct();

如果需要,传递它的参数。

通常,您会在子类的构造函数的开头,在任何特定代码之前这样做;这意味着,就您而言,您将拥有:

class Child extends Base {
function __construct() {
parent::__construct();
echo 'Child __construct<br/>';
}
}


而且,作为引用,您可以查看 PHP 手册的这一页:Constructors and Destructors -- 它声明(引用):

Note: Parent constructors are not called implicitly if the child class defines a constructor.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

关于php - 实例化派生类时是否不隐式调用抽象类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2321009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com