0

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

6
  • 1
    In Hacklang (Facebooks extended PHP language) you can do Vector<Abc> to type hint a Vector (zero indexed list). Sadly PHP itself doesn't offer this afaik, at least not yet. You could hack your way around it though: ensure you are working with "Array of Foo" Commented Apr 3, 2016 at 17:15
  • It's obviously not possible. Commented Apr 3, 2016 at 17:17
  • Why you can Not pass interface abc and need pas array? Commented Apr 3, 2016 at 17:43
  • @Naumov do you suggest passing each and every object individually? the what is the point of arrays? Commented Apr 3, 2016 at 18:33
  • 1
    that's not good idea to pass an array of interfaces. Doing so, you will loose "type hinting" benefits Commented Apr 3, 2016 at 18:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the question is not about ability to accept different interface but rather passing an array of interfaces
I'm sorry, it looks like I misunderstood the question. I updated my answer.
0

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
   }
}

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.