PHP 类型提示特性 [英] PHP type-hinting traits

查看:40
本文介绍了PHP 类型提示特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特点.出于创造力的考虑,我们将这种特质称为 Trait:

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
    }
}

现在,我还有一个使用这个特性的类,User.当尝试使用 User 实例调用 Treat 时,一切正常.但我想提示一下,只有使用 Trait 的类的实例才能作为参数给出,如下所示:

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

遗憾的是,这会导致一个致命错误,该错误表明该函数需要一个 Trait 实例,但给出了一个 User 实例.这种类型的类型提示非常适合继承和实现,但我如何对 trait 进行类型提示?

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?

推荐答案

你不能像 DaveRandom 所说的那样.你不应该.您可能想要实现一个接口和类型提示.然后,您可以使用 trait 来实现该接口.

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.

这篇关于PHP 类型提示特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆