由PHP中的getIterator返回的数组IteratorAggregate不可遍历

McS*_*man 3 php arrays iterator class

我正在尝试使用PHP IteratorAggregate,但没有太多运气.实现IteratorAggregate的对象具有属性$ items,它是一个对象My_Object的数组.

当用户使用带有My_Collection实例的foreach语句时,我希望它迭代$ items数组......但是下面的代码似乎没有按预期工作.

class My_Object {

    public $value;

    public function __construct( $value ) {
        $this->value = $value;
    }

}

class My_Collection implements IteratorAggregate {

    protected $items = array();

    public function add_item( $value ) {
        array_push( $this->items, new My_Object( $value ) );
    }

    public function getIterator() {
        return $this->items;
    }
}

$my_collection = new My_Collection();
$my_collection->add_item( 1 );
$my_collection->add_item( 2 );
$my_collection->add_item( 3 );

foreach( $my_collection as $mine ) {
    echo( "<p>$mine->value</p>" );
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

<b>Fatal error</b>:  Uncaught exception 'Exception' with message 'Objects returned by My_Collection::getIterator() must be traversable or implement interface Iterator' in [...][...]:29
Stack trace:
#0 [...][...](29): unknown()
#1 {main}
thrown in <b>[...][...]</b> on line <b>29</b><br />
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

小智 6

您应该在getIterator中返回一个Iterator.您可以尝试ArrayIterator.

public function getIterator() {
    return new ArrayIterator($this->items);
}
Run Code Online (Sandbox Code Playgroud)