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

2022-08-30 06:11:25

我需要让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
    }
}

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


答案 1

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

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

答案 2

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


推荐