This question already has an answer here:
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
</div>
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
}
}
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();
}
}
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.