【问题标题】:What does the Interface object means in the function parameters [duplicate]函数参数中的接口对象是什么意思[重复]
【发布时间】:2019-06-22 10:50:04
【问题描述】:

我无法理解将任何模型或接口对象放入方法参数的含义。 例如,

public function checkRights(CommentInterface $comment)
{
    return true;
}

那么,CommentInterface 是做什么的呢?为什么我们不仅在这里传递 $comment ?这种东西在编程语言中是怎么命名的?

我是面向对象的 php 新手 谢谢。

【问题讨论】:

  • 这是一个类型提示。这意味着$comment 必须是实现CommentInterface 接口的对象。见the documentation

标签: php laravel oop yii


【解决方案1】:

这称为类型提示

类型提示 强制您只传递特定类型的对象。这可以防止您传递不兼容的值,并在您与团队等合作时创建标准,

检查以下示例:

class Profile {
private $setting;
public function __construct(Setting $setting)
    {
        $this->setting = $setting;
    }
}

因为我们需要在函数内部使用$setting对象,所以我们将它作为参数注入/传递/类型提示。

【讨论】:

  • 不,那不是 DI。 CommentInterface 是一个简单的类型提示,并不是所有的类型提示都引用 DI
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 2020-02-27
  • 1970-01-01
  • 2020-12-12
相关资源
最近更新 更多