Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an interface that functions as an Iterator using generator?

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?


1 Answers

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";
}
like image 63
salathe Avatar answered Oct 24 '25 20:10

salathe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!