为类php配置自己的迭代器? [英] configure own iterator for class php?

查看:143
本文介绍了为类php配置自己的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class Foo, I need to do :

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

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

and define my own method to iterate with this object, exemple :

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;
    }
}

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

Can we do that? How?

推荐答案

你需要实现 \ Iterator \ IteratorAggregate 接口实现了这一点。

You need to implement the \Iterator or \IteratorAggregate interface to achieve that.

使用\ IteratorAggregate和\Iterator接口尝试实现的一个简单示例(我已经遗漏了\ Iterator实现细节,但您可以使用PHP文档查看它们的工作原理):

A simple example of what you're trying to achieve using the \IteratorAggregate and \Iterator interfaces (I've left out the \Iterator implementation details, but you can use the PHP doc to see how they work) :

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;
}

这篇关于为类php配置自己的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆