May I use properties from a parent class in a trait?
Asked Answered
C

2

14

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();
  }
}
Charo answered 18/1, 2017 at 6:2 Comment(2)
This should be in codereview.stackexchange.comBiblical
I posted an example, this is not code to reviewCharo
D
19

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.

Dodwell answered 18/1, 2017 at 6:38 Comment(2)
I've thought of solution #2, but one more argument... not sexy, Some of my methods already have 3Charo
ended up with solution #2Charo
C
1

A Trait intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance. {Official PHP documentation}

Methods defined in traits can access methods and properties of the class they're used in, including private ones!!!

In other words, Trait is an extension of the code (addition)! So using properties/methods from bases/parent classes in trait is not bad practice! Traits were designed for this.

Caboose answered 20/5, 2023 at 5:42 Comment(2)
Yep, I agree that it's possible to reference property of the class in trait. What is not clear to me - when writing trait implementation how you can guarantee that this property exists in the class? From the example above, if class doesn't have model property it still will be able to use ExampleTrait and you will not get FatalError.Theory
From the example above, if class Base doesn't have model property you will GET FatalError in $this->model->doSomething();.Caboose

© 2022 - 2025 — McMap. All rights reserved.