小编典典

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

all

我需要在 PHP 中有一个类构造函数调用其父级的 级(祖父母?)构造函数而不调用父构造函数。

// 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
    }
}

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


阅读 137

收藏
2022-05-20

共1个答案

小编典典

丑陋的解决方法是将一个布尔参数传递给 Papa,表明您不希望解析其构造函数中包含的代码。IE:

// 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);
    }
}
2022-05-20