Reputation: 29390
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?
Upvotes: 43
Views: 18799
Reputation: 3168
try this:
/**
* @param Trait $instance
*/
static function treat($instance){
}
This works on Intellij Idea, but your example doesn't make a lot of sense anyways, trait is not class or interface it's just a portion of code which gets places where ever you use it, so don't do this, use parent classes which use these traits for example that could be your right solution.
However the piece of code I wrote above works and I got auto-completion.
Upvotes: 1
Reputation: 888
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){...}
Upvotes: 4
Reputation: 379
For people ending up here in the future, I would like to elaborate on Veda's answer.
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.
Upvotes: 15
Reputation: 2073
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.
Upvotes: 19