Pass an array of interfaces into a function? [duplicate]

北慕城南 提交于 2019-12-12 03:48:59

问题


In PHP since the interface benefits can used by passing as parameter mentioning the Interface name something like

public function foo (Abc $abc){}

where Abc is an interface.But how do I pass an array of these interfaces?

Please note this not class but interface and only way to get advantage of interface is passing as function with type hinting


回答1:


In PHP 5.6+ you could do something like this:

function foo(Abc ...$args) {

}

foo(...$arr);

foo() takes a variable amount of arguments of type Abc, and by calling foo(...$arr) you unpack $arr into a list of arguments. If $arr contains anything other than instances of Abc an error will be thrown.

This is a little 'hacky', but it's the only way to get type hinting for an array in PHP, without putting down some extra code.




回答2:


Unfortunately, you cannot check for two different interfaces at the same time using type hinting in PHP, but you can write a function for this which will check if the object belongs to multiple interfaces, eg -

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

You can then use it like this,

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



回答3:


if you use PHP 5.6+ you can use variadic with decorator pattern:

<?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();
    }
}


来源:https://stackoverflow.com/questions/36388466/pass-an-array-of-interfaces-into-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!