5

I have a trait and would like to type hint $this to inform the compiler of it's type:

trait MyTrait {
  public function myAwesomeFunction() {
    return new OtherClass($this); // warning: Expected MyAwesomeInterface, got MyTrait
  }
}

class OtherClass {
  public function __construct(MyAwesomeInterface $foo) { ... }
}

So I wonder if there is something equivalent to, e.g.:

trait MyTrait {
  public function myAwesomeFunction() {
    /**
     *  @var $this MyAwesomeInterface
     */
    return new OtherClass($this); // no warnings
  }
}

That would allow me to inform the compiler that users of the trait implement my interface.

Note that a trait cannot implement an interface in PHP (see Why PHP Trait can't implement interfaces?).

Thank you for any help ;-)

Vincent Pazeller
  • 1,448
  • 18
  • 28

1 Answers1

0

No warning because you cheated IDE param is passed correctly. Actually, when running it always throw error.

Trait is chunks of relevant functions injected in for any class in PHP. It's aim to not used for OOP. I think it will help for Utilities support functions.

Viet Dinh
  • 1,871
  • 1
  • 6
  • 18