PHP type-hinting traits

2019-04-03 07:36发布

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?

1条回答
Evening l夕情丶
2楼-- · 2019-04-03 08:23

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.

查看更多
登录 后发表回答