33
votes

I have a trait. For the sake of creativity, let's call this trait Trait:

trait Trait{    
    static function treat($instance){    
        // treat that trait instance with care
    }
}

Now, I also have a class that uses this trait, User. When trying to call treat with an instance of User, everything works. But I would like to type-hint that only instances of classes using Trait should be given as arguments, like that:

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

Sadly, though, this results in a fatal error that says the function was expecting an instance of Trait, but an instance of User was given. That type of type-hinting works perfectly for inheritance and implementation, but how do I type-hint a trait?

3
DaveRandom is correct, you need to use use statements to implement traits as they are not instantiated.phpisuber01
@DaveRandom i think this is another php wtf see eval.in/5936 if its not going to be treated as a class why are you getting Fatal error: Cannot redeclare class HelloBaba
Thanks guys. @DaveRandom: Sorry, I did not see it in the manual. Thanks for the link.arik
This is dumb. The dumbest part if that PHP actually has this type information at run-time - you can manually type-check against traits using reflection, and traits for that matter are actually reflected using ReflectionClass. For all intents and purposes, traits are abstract classes that can be mixed-in - since this is done statically, why on Earth would you not allow type-checking? Seems really daft.mindplay.dk

3 Answers

18
votes

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.

9
votes

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.

2
votes

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){...}