【问题标题】:When I create a supertype class and extend it, what happens to the constructor of the supertype?当我创建一个超类型类并扩展它时,超类型的构造函数会发生什么?
【发布时间】:2011-11-17 05:29:29
【问题描述】:

我可以扩展 sueprtype 的构造函数吗?文档没有说明扩展功能。

我想创建一个在初始化子类型时连接到数据库的类,但我不想为每个子类型编写连接代码。所以我想在超类型的构造函数中这样做,但我也希望子类型有构造函数。

【问题讨论】:

标签: php oop class inheritance


【解决方案1】:

是的,您可以像类中的任何其他方法一样覆盖构造函数:

<?php
class DbSuper {
    function __construct() {
        echo "db connection using super class<br/>";
    }
}

class DbSub extends DbSuper {
    function __construct() {
        echo "db connection using sub class<br/>";
    }
}

class DbSubNoConstr extends DbSuper {

}

class DbSubBothConstr extends DbSuper {
    function __construct() {
        echo "execute subclass code<br/>";
        parent::__construct();
    }

}

new DbSub(); //prints db connection using sub class
new DbSubNoConstr(); // prints db connection using super class
new DbSubBothConstr(); // prints execute subclass code db connection using super class
?>

【讨论】:

    【解决方案2】:

    方法本身并没有得到“扩展”;课程得到扩展。这些类的方法仍然存在,并且可以在适当的范围内调用。

    要更直接地回答您的问题,您可以调用parent::__construct() 来调用超类的__construct() 方法。请参阅the PHP documentation on constructors and destructors 了解更多信息。

    【讨论】:

      【解决方案3】:

      来自 php.net

      注意:如果子类不隐式调用父构造函数 定义了一个构造函数。为了运行父构造函数,调用 子构造函数中的 parent::__construct() 是必需的。

      http://www.php.net/manual/en/language.oop5.decon.php

      所以你要做的是在超类构造函数中连接到数据库。然后创建你的子类构造函数并调用parent::__construct()

      但是,显式连接可能会更好。在基类调用$this-&gt;connect(),它会在父类中定义。

      【讨论】:

        【解决方案4】:

        正如您可以使用parent::methodName() 调用父版本的函数一样,您也可以调用self::methodName() 来调用方法的当前类实现。

        这个链接可能对你有帮助

        http://www.php.net/manual/en/language.oop5.basic.php#102275

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-24
          • 2014-11-27
          • 2021-02-13
          • 1970-01-01
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          相关资源
          最近更新 更多