update page now

Класс CachingIterator

(PHP 5, PHP 7, PHP 8)

Введение

Этот объект поддерживает кеширование итерации над другим итератором.

Обзор класса

class CachingIterator extends IteratorIterator implements ArrayAccess, Countable, Stringable {
/* Константы */
public const int CALL_TOSTRING;
public const int CATCH_GET_CHILD;
public const int TOSTRING_USE_KEY;
public const int TOSTRING_USE_INNER;
public const int FULL_CACHE;
/* Методы */
public function __construct(Iterator $iterator, int $flags = CachingIterator::CALL_TOSTRING)
public function count(): int
public function current(): mixed
public function getCache(): array
public function getFlags(): void
public function hasNext(): bool
public function key(): scalar
public function next(): void
public function offsetExists(string $key): bool
public function offsetGet(string $key): mixed
public function offsetSet(string $key, mixed $value): void
public function offsetUnset(string $key): void
public function rewind(): void
public function setFlags(int $flags): void
public function __toString(): string
public function valid(): bool
/* Наследуемые методы */
public function IteratorIterator::current(): mixed
public function IteratorIterator::key(): mixed
public function IteratorIterator::next(): void
public function IteratorIterator::rewind(): void
public function IteratorIterator::valid(): bool
}

Предопределённые константы

CachingIterator::CALL_TOSTRING

Преобразует каждый элемент в строку.

CachingIterator::CATCH_GET_CHILD

Не выбрасывать исключения при доступе к дочерним элементам.

CachingIterator::TOSTRING_USE_KEY

Использовать ключ при преобразовании в строку.

CachingIterator::TOSTRING_USE_CURRENT

Использовать текущий элемент при преобразовании в строку.

CachingIterator::TOSTRING_USE_INNER

Использовать внутренний итератор при преобразовании в строку.

CachingIterator::FULL_CACHE

Кеширование всей прочтённой информации.

Список изменений

Версия Описание
8.0.0 Класс CachingIterator теперь реализует интерфейс Stringable.

Содержание

Добавить

Примечания пользователей 4 notes

up
17
ahmad dot mayahi at gmail dot com
6 years ago
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.
up
9
ahmad dot mayahi at gmail dot com
9 years ago
<?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());
?>
up
5
jerome at chaman dot ca
6 years ago
"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)
up
0
xedin dot unknown at gmail dot com
6 years ago
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.
To Top