为php类配置自己的迭代器


configure own iterator for class php?

我有一个Foo类,我需要做:

$foo = new Foo();
foreach($foo as $value)
{
    echo $value;
}

并定义我自己的方法来迭代这个对象,例如:

class Foo
{
    private $bar = [1, 2, 3];
    private $baz = [4, 5, 6];

    function create_iterator()
    {
        //callback to the first creation of iterator for this object
        $this->do_something_one_time();
    }
    function iterate()
    {
        //callback for each iteration in foreach
        return $this->bar + $this->baz;
    }
}

我们能做到吗?怎样

您需要实现''Iterator或''IteratorAggregate接口来实现这一点。

使用''IteratorAggregate和''Iterator接口(我省略了''Iterater实现的详细信息,但您可以使用PHP文档来查看它们的工作方式)来实现什么的一个简单示例:

class FooIterator implements 'Iterator
{
    private $source = [];
    public function __construct(array $source) 
    {
        $this->source = $source;
        // Do whatever else you need
    }
    public function current() { ... }
    public function key() { ... }
    public function next() 
    {
        // This function is invoked on each step of the iteration
    }
    public function rewind() { ... }
    public function valid() { ... }
}

class Foo implements 'IteratorAggregate
{
    private $bar = [1, 2, 3];
    private $baz = [4, 5, 6];
    public function getIterator()
    {
        return new FooIterator(array_merge($this->bar, $this->baz));
    }
}
$foo = new Foo();
foreach ($foo as $value) {
    echo $value;
}