Search code examples
phptraits

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


Is it OK to use properties/methods from parent classes in trait methods?

This code works, but is it good practice?

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

Solution

  • I don't think it's good practice.

    Instead you could have a method to fetch your model object, and have that method as an abstract signature in you trait:

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

    Or pass your model as a parameter to your trait method:

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

    Both of these approaches let you utilize your IDE's type hinting.