首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让PHP类构造函数调用其父类的构造函数?

如何让PHP类构造函数调用其父类的构造函数?
EN

Stack Overflow用户
提问于 2009-10-13 00:09:05
回答 14查看 288.8K关注 0票数 254

我需要让PHP中的一个类构造函数调用其父对象的父对象的(祖父母?)构造函数,而不调用父构造函数。

代码语言:javascript
复制
// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {

    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        // THIS IS WHERE I NEED TO CALL GRANDPA'S
        // CONSTRUCTOR AND NOT PAPA'S
    }
}

我知道这是一件奇怪的事情,我正在尝试找到一种不那么难闻的方法,但尽管如此,我还是很好奇这是否可能。

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2009-10-13 00:28:01

丑陋的变通办法是向Papa传递一个布尔参数,表明您不希望解析它的构造函数中包含的代码。即:

代码语言:javascript
复制
// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {

    }

}

class Papa extends Grandpa
{
    public function __construct($bypass = false)
    {
        // only perform actions inside if not bypassing
        if (!$bypass) {

        }
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        $bypassPapa = true;
        parent::__construct($bypassPapa);
    }
}
票数 209
EN

Stack Overflow用户

发布于 2009-10-13 00:18:00

您必须使用Grandpa::__construct(),没有其他快捷方式可以使用它。此外,这还会破坏Papa类的封装-当读取或处理Papa时,可以安全地假定__construct()方法将在构造期间被调用,但Kiddo类不会这样做。

票数 87
EN

Stack Overflow用户

发布于 2012-01-18 19:51:07

代码语言:javascript
复制
class Grandpa 
{
    public function __construct()
    {}
}

class Papa extends Grandpa
{
    public function __construct()
    {
        //call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        //this is not a bug, it works that way in php
        Grandpa::__construct();
    }
}
票数 55
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1557608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档