【问题标题】:Pass an array of interfaces into a function? [duplicate]将一组接口传递给函数? [复制]
【发布时间】:2016-04-03 17:09:32
【问题描述】:

在 PHP 中,接口的好处可以通过作为参数传递来提及接口名称来使用

public function foo (Abc $abc){}

其中 Abc 是一个接口。但是如何传递这些接口的数组?

请注意,这不是类,而是接口,获得接口优势的唯一方法是作为带有类型提示的函数传递

【问题讨论】:

  • 在 Hacklang(Facebook 的扩展 PHP 语言)中,您可以通过 Vector<Abc> 输入提示向​​量(零索引列表)。遗憾的是 PHP 本身不提供这个 afaik,至少现在还没有。不过你可以破解它:ensure you are working with "Array of Foo"
  • 显然不可能。
  • 为什么不能通过接口abc需要pas数组?
  • @Naumov 你建议单独传递每个对象吗?数组的意义何在?
  • 传递接口数组不是一个好主意。这样做,您将失去“类型提示”的好处

标签: php interface


【解决方案1】:

在 PHP 5.6+ 中你可以这样做:

function foo(Abc ...$args) {

}

foo(...$arr);

foo() 接受可变数量的Abc 类型的参数,并通过调用foo(...$arr)$arr 解包到参数列表中。如果$arr 包含除Abc 实例以外的任何内容,则会引发错误。

这有点“hacky”,但它是在 PHP 中获取数组类型提示的唯一方法,而无需编写一些额外的代码。

【讨论】:

  • 问题不在于接受不同接口的能力,而是传递一个接口数组
  • 对不起,我好像误解了这个问题。我更新了我的答案。
【解决方案2】:

不幸的是,您不能在 PHP 中使用type hinting 同时检查两个不同的接口,但是您可以为此编写一个函数来检查对象是否属于多个接口,例如 -

function belongs_to_Interfaces($obj,array $interfaces)
{
    foreach($interfaces as $interface)
    {
         if(!is_a($obj,$interface))
         {
             return false;
         }
    }
    return true;
}

你可以这样使用它,

public function foo ($abc){
  if(!belongs_to_Interfaces($abc, ['interface1', 'interface2'])){
      //throw an error or return false
   }
}

【讨论】:

    【解决方案3】:

    如果你使用 PHP 5.6+,你可以使用带有装饰器模式的可变参数:

    <?php
    
    interface Rule {
        public function isSatisfied();
    }
    
    final class ChainRule implements Rule {
        private $rules;
    
        public function __construct(Rule ...$rules) {
            $this->rules = $rules;
        }
    
        public function isSatisfied() {
            foreach($this->rules as $rule)
                $rule->isSatisfied();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 2012-05-25
      • 2016-02-07
      相关资源
      最近更新 更多