Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top