doubi1910 2015-03-23 16:26
浏览 38
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • dpli36193 2015-03-23 16:34
    关注

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

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?