在trait中执行构造函数

问题描述 投票:4回答:1

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

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

class myClass{
    use test;
    public function __construct(){
        echo 'myClass';
    }
}
new myClass();
php traits
1个回答
7
投票

试试这样(test):

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

class myClass{
    use test {
        test::__construct as private __tConstruct;
    }
    public function __construct(){
        $this->__tConstruct();
    }
}
new myClass();
© www.soinside.com 2019 - 2024. All rights reserved.