The CachingIterator class

(PHP 5, PHP 7)

简介

This object supports cached iteration over another iterator.

类摘要

CachingIterator extends IteratorIterator implements OuterIterator , ArrayAccess , Countable {
/* 常量 */
const integer CALL_TOSTRING = 1 ;
const integer CATCH_GET_CHILD = 16 ;
const integer TOSTRING_USE_KEY = 2 ;
const integer TOSTRING_USE_CURRENT = 4 ;
const integer TOSTRING_USE_INNER = 8 ;
const integer FULL_CACHE = 256 ;
/* 方法 */
public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public count ( void ) : int
public current ( void ) : mixed
public getCache ( void ) : array
public getFlags ( void ) : int
public getInnerIterator ( void ) : Iterator
public hasNext ( void ) : void
public key ( void ) : scalar
public next ( void ) : void
public offsetExists ( mixed $index ) : void
public offsetGet ( string $index ) : void
public offsetSet ( mixed $index , mixed $newval ) : void
public offsetUnset ( string $index ) : void
public rewind ( void ) : void
public setFlags ( int $flags ) : void
public __toString ( void ) : void
public valid ( void ) : void
}

预定义常量

CachingIterator::CALL_TOSTRING

Convert every element to string.

CachingIterator::CATCH_GET_CHILD

Don't throw exception in accessing children.

CachingIterator::TOSTRING_USE_KEY

Use key for conversion to string.

CachingIterator::TOSTRING_USE_CURRENT

Use current for conversion to string.

CachingIterator::TOSTRING_USE_INNER

Use inner for conversion to string.

CachingIterator::FULL_CACHE

Cache all read data.

Table of Contents

User Contributed Notes

jerome at chaman dot ca 15-Dec-2019 12:37
"cached iteration over another iterator" means this iterator is always one step behind the inner iterator. In other words, the "first" iteration will yield null:

<?php

$cit
= new CachingIterator( new ArrayIterator( [ 'a', 'b', 'c']  ) );

echo
$cit->current() ); // null
echo $cit->getInnerIterator()->current() ); // "a"

while($cit->hasNext()){
   
   
// we start with a "next" since the "first" item is null
    
$cit->next();
     echo
$cit->current(), '<br>';
  
}
?>

iterating this way gives us an access, ahead, to the future item (aka current item of the inner iterator)
ahmad dot mayahi at gmail dot com 24-Oct-2016 07:54
<?php
//This snippet will print out all the cached elements (foreach) .

$cache  = new CachingIterator(new ArrayIterator(range(1,100)), CachingIterator::FULL_CACHE);

foreach (
$cache as $c) {

}

print_r($cache->getCache());
?>