PHP 类型提示特征

标签 php traits type-hinting

我有一个特点。为了创意起见,我们称这个特质为 Trait:

trait Trait{    
    static function treat($instance){    
        // treat that trait instance with care
    }
}

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

static function treat(Trait $instance){...}

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

最佳答案

你不能像 DaveRandom 说的那样。你不应该。您可能想要实现一个接口(interface)并在其上进行类型提示。然后,您可以使用特征实现该接口(interface)。

关于PHP 类型提示特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14157586/

相关文章:

PHP 使用多个 while 循环仅检索 1 行

scala - super 链式 Scala 特征的行为

rust - 如何从Box <dyn AsRef <Path >>中提取impl AsRef <Path>值?

php - 类型提示一个类作为具有不同命名空间的另一个类的参数

Javascript 混淆 AJAX 代码

php - 使用复选框更新数据库列

带有引用的 Rust 泛型 AddAssign

python - 在 PyCharm 中类型提示 dict.items() 时的奇怪行为

php - 在忽略参数类型提示的同时调用 PHP 方法

php - 使用带有多选复选框的 Ajax 帖子过滤器获取帖子