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, "\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With