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

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

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

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的类型提示.

上一篇:php – 如何(以及在​​何处)在Laravel中注册自定义查询方法


下一篇:php – 无法访问trait中的受保护属性