dgifford/iterator-trait

Trait providing methods implementing the Iterator interface.

v2.0 2024-06-07 14:16 UTC

This package is auto-updated.

Last update: 2024-11-07 15:05:57 UTC


README

Provides methods for implementing the iterator interface allowing objects to be iterated with a foreach loop.

The trait adds a private property $container to hold the items that are iterated and a private property $position which hold the current position in $container.

Classes must implement the iterator interface.

class Foo implements \Iterator
{
    Use IteratorTrait;

    public function add( mixed $item ): void
    {
        $this->container[] = $item;
    }
}


$this->foo = new Foo;

$this->foo->add( 'zero' );
$this->foo->add( 'one' );
$this->foo->add( 'two' );

foreach( $this->foo as $key => $value )
{
	echo "$key => $value";
}

// 0 => zero
// 1 => one
// 2 => two