为类php配置自己的迭代器?

时间:2015-03-23 16:26:53

标签: php class iterator

我有一个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;
    }
}

我们可以这样做吗?怎么样?

2 个答案:

答案 0 :(得分:1)

您需要实现Iterator界面。

class Foo implements Iterator {

您应该查看内置界面:

http://php.net/manual/en/reserved.interfaces.php

答案 1 :(得分:1)

您需要实现\Iterator\IteratorAggregate界面才能实现这一目标。

使用\ IteratorAggregate和\ Iterator接口尝试实现的一个简单示例(我省略了\ Iterator实现细节,但您可以使用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;
}