I want to create a directory class, and I want it to function as an iterator (foreach-able). But I want it to be generator based (for example a function that does "yield"). Is it possible?
There is not an interface explicitly for classes to implement generators, but you can make use of IteratorAggregate
here.
See this example of implementing IteratorAggregate
from the Generators RFC
class Test implements IteratorAggregate {
protected $data;
public function __construct(array $data) {
$this->data = $data;
}
public function getIterator() {
foreach ($this->data as $key => $value) {
yield $key => $value;
}
// or whatever other traversation logic the class has
}
}
$test = new Test(['foo' => 'bar', 'bar' => 'foo']);
foreach ($test as $k => $v) {
echo $k, ' => ', $v, "
";
}
Generators are Iterators.
From http://www.php.net/manual/en/language.generators.object.php
When a generator function is called for the first time, an object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would.