dgifford/iterator-trait

提供实现 Iterator 接口方法的特质。

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

This package is auto-updated.

Last update: 2024-09-07 14:51:19 UTC


README

提供实现迭代器接口的方法,允许对象通过 foreach 循环进行迭代。

该特质添加一个私有属性 $container 来存储迭代的项,以及一个私有属性 $position 来存储在 $container 中的当前位置。

类必须实现迭代器接口。

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