迭代作为Traversable的特征

时间:2014-11-24 23:49:16

标签: php

我想使用名为Iterative的特性制作一个PHP的迭代器。我试着这样做:

  1. Trait Iterative“实现”界面Traversable

    trait Iterative
    {
        public function rewind(){ /* ... */ }
        public function current(){ /* ... */ }
        public function key(){ /* ... */  }
        public function next(){ /* ... */ }
        public function valid(){ /* ... */ }
    }
    
  2. 类BasicIterator应使用trait

    实现接口
    class BasicIterator implements \Traversable {
        use Iterative;
    }
    
  3. 但我明白了:

        Fatal error: Class BasicIterator must implement interface Traversable as part of either Iterator or IteratorAggregate in Unknown on line 0
    

    它甚至可能以什么方式存在?

2 个答案:

答案 0 :(得分:4)

问题不在于使用Traits,而是因为您正在实现错误的界面。请参阅the manual page for Traversable上的此说明:

  

这是一个内部引擎接口,无法在PHP脚本中实现。必须使用IteratorAggregate或Iterator。

改为class BasicIterator implements \Iterator,因为that is the interface whose methods you have included in your Trait

答案 1 :(得分:2)

我相信你必须实现Iterator或IteratorAggregate,例如:

<?php
trait Iterative
{
    public function rewind(){ /* ... */ }
    public function current(){ /* ... */ }
    public function key(){ /* ... */  }
    public function next(){ /* ... */ }
    public function valid(){ /* ... */ }
}

# Class BasicIterator should implements the interface using trait

class BasicIterator implements \Iterator {
    use Iterative;
}
?>

请参阅http://3v4l.org/G7KiF

相关问题