ari*_*rik 25 php traits type-hinting
我有一个特点.为了创造力,让我们称之为特质Trait:
trait Trait{
static function treat($instance){
// treat that trait instance with care
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我还有一个使用这个特性的类,User.当尝试使用User实例调用treat时,一切正常.但我想输入提示,只有使用Trait的类的实例应该作为参数给出,如下所示:
static function treat(Trait $instance){...}
Run Code Online (Sandbox Code Playgroud)
但遗憾的是,这会导致致命的错误,该错误表明该函数期待Trait的一个实例,但是给出了一个User实例.这种类型的提示适用于继承和实现,但我如何键入提示特征?
Ved*_*eda 16
DaveRandom说,你不能.你不应该.您可能希望在其上实现接口和typehint.然后,您可以使用特征实现该接口.
对于将来在这里结束的人,我想详细说明吠陀的答案。
综上所述; 你的想法不是疯狂的!实际上,将特征视为该词的常识是很有意义的,而其他语言也是如此。由于某种原因,PHP 似乎卡在接口和特征之间。