Provides an iterator implementation based on a closure factory.
Description
This class allows dynamic generation of iterators using a provided closure. It is particularly useful in scenarios where deferred computation or dynamic iterable generation is needed.
Usage Examples:
Using Generator Function:
Description
use FastForward\Iterator\ClosureFactoryIteratorAggregate;
$iterator = new ClosureFactoryIteratorAggregate(function () {
yield 1;
yield 2;
yield 3;x
});
foreach ($iterator as $value) {
echo $value; // Outputs: 1 2 3
}
Using Array Iterator:
Description
use FastForward\Iterator\ClosureFactoryIteratorAggregate;
use ArrayIterator;
$array = [10, 20, 30];
$iterator = new ClosureFactoryIteratorAggregate(fn () => new ArrayIterator($array));
foreach ($iterator as $value) {
echo $value; // Outputs: 10 20 30
}
Generator with return Statement:
Description
use FastForward\Iterator\ClosureFactoryIteratorAggregate;
$iterator = new ClosureFactoryIteratorAggregate(
fn () => (function () {
yield 'A';
yield 'B';
return 'This will not be iterated';
})()
);
foreach ($iterator as $value) {
echo $value; // Outputs: A B
}
Note: If a Generator function includes a return statement,
its return value will not be iterated.
Properties
Methods
Initializes the ClosureFactoryIteratorAggregate with a closure.
Counts the number of elements exposed by the inner iterator.
Retrieves the iterator generated by the factory closure.
Initializes the ClosureFactoryIteratorAggregate with a closure.
public
__construct(Closure
$factory) : mixed
Parameters
$factory
:
Closure
Description
a function that returns an iterable structure
Counts the number of elements exposed by the inner iterator.
public
count() : int
Description
If the inner iterator implements Countable, this method SHALL return the value provided by that implementation. Otherwise, it MUST count elements by iterating over the iterator. If the inner iterator is not cloneable, this method SHALL wrap the current object in an IteratorIterator instance and count through that wrapper to avoid performing an invalid clone operation. If the inner iterator is cloneable, this method SHOULD count over a clone so that the original iterator state is preserved as much as possible.
Return values
Description
the total number of elements available from the inner iterator
Retrieves the iterator generated by the factory closure.
public
getIterator() : Traversable
Description
This method invokes the provided closure and returns the resulting Traversable instance.
Important: If the generator contains a return statement, its return value will not be iterated.
Return values
Description
the iterator generated by the factory function