实例化派生类时,是否隐式调用了抽象类构造函数? [英] Are abstract class constructors not implicitly called when a derived class is instantiated?

查看:99
本文介绍了实例化派生类时,是否隐式调用了抽象类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个示例为例:

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

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

$c = new Child();   

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

Coming from a C# background, I expect the output to be


基础__construct
子__construct

Base __construct
Child __construct

但是,实际输出是只是


孩子__construct

Child __construct


推荐答案

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

No, the constructor of the parent class is not called if the child class defines a constructor.

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

From the constructor of your child class, you have to call the constructor of the parent's class :

parent::__construct();

根据需要传递参数。

通常,您将在子类的构造函数的开始,在任何特定的代码之前执行此操作;这意味着,在您的情况下,您将:

Generally, you'll do so at the beginning of the constructor of the child class, before any specific code ; which means, in your case, you'd have :

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



,您可以查看PHP手册的以下页面:构造函数和析构函数-声明(quoting)


注意:父级构造函数如果子类
定义了构造函数,则不会隐式调用。
为了使
运行父构造函数,在
子构造函数中调用
parent :: __ construct()

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.

这篇关于实例化派生类时,是否隐式调用了抽象类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆