我可以在特征中使用父 class 的属性吗?

May I use properties from a parent class in a trait?

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

此代码有效,但它是好的做法吗?

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

我认为这不是个好习惯。

相反,你可以有一个方法来获取你的模型对象,并将该方法作为你特征中的抽象签名:

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

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

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

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