Multiple inheritance + Multi-Level inheritance in PHP: 是否有解决构造函数继承的模式或可能性?

Multiple inheritance + Multi-Level inheritance in PHP: Is there a pattern or possibility to solve constructor inheritance?

看看下面的例子:

class A {
    protected $a;
    public function __construct() {
        $this->a = "foo";
    }
}

trait Q {
    protected $q;
    public function __construct() {
        $this->q = "happy";
    }
}

class B extends A {
    use Q;
    protected $b;
    public function __construct() {
        $this->b = "bar";
    }
}

trait X {
    protected $x;
    public function __construct() {
        $this->x = "lorem";
    }
}

class C extends B {
    use X;
    protected $c;
    public function __construct() {
        $this->c = "sure";
    }

    public function giveMeEverything() {
        echo $this->a." ".$this->b." ".$this->c." ".$this->x." ".$this->q;
    }
}

$c = new C();
$c->giveMeEverything();

这工作得很好 - 输出是:

sure

问题是我想要树中的所有 类 和 traits 来初始化它们的成员变量。期望的输出:

foobarsureloremhappy

一定不能用构造函数解决!我只想在初始化时填充成员变量,但我仍然不知道如何解决这个问题。在现实世界的例子中,这更复杂,因此请不要 $a = "foo"; 只在变量声明中。

问题是特征不能被实例化所以__construct()有点没有意义。

最好的方法是使用 class 构造函数初始化您的成员变量;这就是构造函数存在的原因。

如果你想初始化一些在特征中声明的成员,那么有一个特征函数并在适当的 class 构造函数中调用它,例如:

trait Q {
    protected $a;
    public function initQ() { $this->a = "whatever"; }
}

class MyClass {
    use Q;

    public function __construct() {
        $this->initQ();
    }
}