0

I would like to use traits to instanciate my objects with my DIC:

trait TUseContainer {

    protected $c;

    public function __construct(Container $c) {
        $this->c=$c;
    }

}

class MyClass {
    use TUseContainer;

    //Optional
    public function __construct(ClassInheritedFromContainer $c){
        TUseContainer::__construct($c);
        //MyClass __construct stuff
    }

}

So my questions are:

  1. Does TUseContainer::__construct($c); will work?
  2. If not, does parent::__construct($c); will do the trick? (I think it will not)
  3. Is trait::myOverridedMethod(); a good way to call non static overrided method?
  4. Do you think I should use the "as" keyword? (I think it's a bad idea)
  5. Is "TUseContainer" a good name for what I intend to do?

All coments are welcome, thanks.

I'll do some tests and post results.

Pierre
  • 429
  • 3
  • 15
  • Check this topic http://stackoverflow.com/questions/12478124/how-to-overload-class-constructor-within-traits-in-php-5-4 – Robert Jun 21 '13 at 10:41
  • I have: Fatal error: Non-static method TUseContainer::__construct() cannot be called statically, assuming $this from incompatible context in /path/to/MyClass.php on line 12 – Pierre Jun 21 '13 at 10:46
  • Thanks Robert, but it's not exactly the same because the __construct is inherited and overrided. The precedence change the rules. – Pierre Jun 21 '13 at 10:48

1 Answers1

0

I got some trivial workaround:

trait TUseContainer {

    protected $c;

    public function __construct(Container $c) {
        $this->setContainer($c);
    }

    protected function setContainer(Container $c){
        $this->c=$c;
    }
}

class MyClass {
    use TUseContainer;

    //Optional
    public function __construct(ClassInheritedFromContainer $c){
        $this->setContainer($c);
        //MyClass __construct stuff
    }

}
  1. No
  2. No
  3. No
  4. No
  5. Open

All coments are still welcome

Pierre
  • 429
  • 3
  • 15