可以在特征方法中使用父类的属性/方法吗?
此代码有效,但它是好的做法吗?
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 - 我可以在特征中使用父类的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712413/