PHP type-hinting traits

If you want to create function inside trait or class that uses the trait you can use self as type-hint so your function would look like this.

static function treat(self $instance){...}

For people ending up here in the future, I would like to elaborate on Veda's answer.

  1. It's true that you can't treat traits as traits in PHP (ironically), saying that you expect an object that has some traits is only possible via interfaces (essentially a collection of abstract traits)
  2. Other languages (such as Rust) actually encourage type hinting with traits

In conclusion; your idea is not a crazy one! It actually makes a lot of sense to view traits as what they are in the common sense of the word, and other languages do this. PHP seems to be stuck in the middle between interfaces and traits for some reason.


You can't as DaveRandom says. And you shouldn't. You probably want to implement an interface and typehint on that. You can then implement that interface using a trait.