我可以在特质中使用父类的属性吗?

yma*_*kux 4 php traits

可以在特征方法中使用父类中的属性/方法吗?

这段代码有效,但这是好的做法吗?

class Child extends Base{

  use ExampleTrait;

  public function __construct(){
     parent::__construct();
  }

  public function someMethod(){
    traitMethod();
  }

}

trait ExampleTrait{
  protected function traitMethod(){
    // Uses  $this->model from Base class
    $this->model->doSomething();
  }
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 6

我不认为这是好习惯.

相反,您可以使用方法来获取模型对象,并将该方法作为特征中的抽象签名:

trait ExampleTrait {
    abstract protected function _getModel();

    protected function traitMethod() {
        $this->_getModel()->doSomething();
    }
}

class Base {
    protected $_model;

    protected function _getModel() {
        return $this->_model;
    }
}

class Child extends Base {
    use ExampleTrait;

    public function someMethod() {
        $this->traitMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者将模型作为参数传递给特征方法:

trait ExampleTrait {
    protected function traitMethod($model) {
        $model->doSomething();
    }
}

class Base {
    protected $_model;
}

class Child extends Base {
    use ExampleTrait;

    public function someMethod() {
        $this->traitMethod($this->_model);
    }
}
Run Code Online (Sandbox Code Playgroud)

这两种方法都可以让您利用IDE的类型提示.