I've got a method that accepts an array of rules as an argument.
public function setRule($name, Array $rules) { ... }
The passed in array should only contain objects that implement the IRule
interface, but since I can't type hint the content of an array I would like to know if there's maybe another way of doing it?
I would highly appreciate examples with your answers.
It is not possible in the function header, but you can do instanceof
checks later on.
Example:
foreach ($rules as $r) {
if ($r instanceof IRule) {
do_something();
} else {
raise_error();
}
}
Most people now will suggest to check the Array right when you are inside the method, but better try this way;
Implement an Iterator (this is a class that can be used like an array, with foreach
for example), and pass this iterator to your class:
class IRuleIterator implements Iterator {
private $var = array();
public function __construct($array) {
if (is_array($array)) {
$this->var = $array;
}
}
public function add($element) {
$this->var[] = $element;
return $this;
}
public function rewind() {
reset($this->var);
return $this;
}
public function current() {
return current($this->var);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() instanceof IRule);
}
}
Then your function:
public function setRule($name, IRuleIterator $rules) { /* ... */ }
You can find a full list of those "special PHP objects" which can be implemented here: http://php.net/manual/en/book.spl.php
The ArrayIterator
would be even better for your purpose. There are lots of nice things in the SPL, have a look at it :)