The CachingIterator class

Введение

...

Class synopsis

CachingIterator
class CachingIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator , ArrayAccess , Countable {
/* Methods */
bool hasNext ( void )
void next ( void )
void rewind ( void )
string __toString ( void )
bool valid ( void )
}

Содержание

Коментарии

<?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());
?>
2016-10-24 22:54:20
http://php5.kiev.ua/manual/ru/class.cachingiterator.html
"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)
2019-12-15 02:37:56
http://php5.kiev.ua/manual/ru/class.cachingiterator.html
The only difference between CachingIterator and other Iterators such as ArrayIterator is the hasNext() method.

Since the data will be loaded into the memory, the CachingIterator is able to check whether the given iterator has a next element.

Let's demonstrate this by an example:

<?php
$iterator 
= new CachingIterator(new ArrayIterator(['C''C++''C#''PHP''Python''Go''Ruby']));

foreach (
$iterator as $item) {
    if (
$iterator->hasNext()) {
        echo 
$item.', ';
    } else {
        echo 
'and '.$item;
    }
}

// C, C++, C#, PHP, Python, Go, and Ruby
?>

In this example I check whether the iterator has a next value, if so, I append a comma otherwise "and" will be appended to the last element.
2020-04-26 00:53:22
http://php5.kiev.ua/manual/ru/class.cachingiterator.html
Apparently, the `FULL_CACHE` flag automatically cancels the default flag `CALL_TOSTRING`. This is evident when one of the values cannot be converted to string: with the default `CALL_TOSTRING` flag, it would throw an error; without that flag, or with the `FULL_CACHE` flag, it does not.
2020-05-07 20:19:39
http://php5.kiev.ua/manual/ru/class.cachingiterator.html

    Поддержать сайт на родительском проекте КГБ