在特征中执行构造函数

Bol*_*lek 6 php traits

我不想在特征(或使用特征时使用其他方法)中执行构造函数。可能吗?

trait test{
    public function __construct()
    {
        echo 'test';
    }
}

class myClass{
    use test;
    public function __construct(){
        echo 'myClass';
    }
}
new myClass();
Run Code Online (Sandbox Code Playgroud)

Cla*_*dio 8

像这样尝试(测试):

trait test{
    public function __construct()
    {
        echo 'test';
    }
}

class myClass{
    use test {
        test::__construct as private __tConstruct;
    }
    public function __construct(){
        $this->__tConstruct();
    }
}
new myClass();
Run Code Online (Sandbox Code Playgroud)

  • 类似的答案在这里:/sf/answers/880852241/ (2认同)