PHP.mk документација

IteratorIterator

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.iteratoriterator.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.iteratoriterator.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
IteratorIterator

Референца за `class.iteratoriterator.php` со подобрена типографија и навигација.

class.iteratoriterator.php

Класата IteratorIterator

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Вовед

Овој обвивач на итератор овозможува конверзија на било што што е Траверзабилно во Iterator. Важно е да се разбере дека повеќето класи што не имплементираат итератори имаат причини бидејќи најверојатно не дозволуваат целосен сет на функции на итераторот. Ако е така, треба да се обезбедат техники за спречување на злоупотреба, инаку очекувајте исклучоци или фатални грешки.

Синопсис на класата

class IteratorIterator implements OuterIterator {
/* Методи */
public __construct(Траверзабилно $iterator, ?string $class = null)
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

Белешки

Забелешка:

Оваа класа дозволува пристап до методите на внатрешниот итератор преку магичниот метод __call.

Содржина

Белешки од корисници 4 белешки

sven на rtbg dot de
пред 10 години
This iterator basically is only a wrapper around another iterator. It does nothing fancy, it simply forwards any calls of rewind(), next(), valid(), current() and key() to the inner iterator. This inner iterator can be fetched with getInnerIterator().

One special case: When passing an IteratorAggregate object, the getIterator() method of that object will be called and THAT iterator will be iterated over, and this will also be returned when calling getInnerIterator().

This class can be extended, so it's an ideal building block for your own classes that only want to modify one or two of the iterator methods, but not all.

Want to trim the strings returned by the current() method?

<?php

class TrimIterator extends IteratorIterator
{
    public function current() {
        return trim(parent::current());
    }
}

$innerIterator = new ArrayIterator(array('normal', ' trimmable '));

$trim = new TrimIterator($innerIterator);

foreach ($trim as $key => $value) {
    echo "Key:\n";
    var_dump($key);
    echo "Value:\n";
    var_dump($value);
    echo "---next---";
}
?>

Output:

Key:
int(0)
Value:
string(6) "normal"
---next---Key:
int(1)
Value:
string(9) "trimmable"
---next---
max-p на max-p точка me
пред 10 години
Little note for anyone that wants to emulate the behavior of foreach as close as possible in order to work with somewhat picky Traversable objects, without using foreach:

- Before starting the iteration, rewind() is called.
- For every iteration, the following methods are called on the iterator:
    - valid()
    - current()
    - key()
    - next()

Sounds like a silly thing to do put this way, but in my use case I needed to convert a Traversable database result cursor into a procedural-style cursor (hasNext + fetchArray) for backward compatibility, and the driver required every function to be called in the appropriate order.
wallacemaxters на gmail точка lcom
пред 10 години
Another example of the efficiency for IteratorIterator is a small class for enumerate for iterations of an interator implementation.

Example:

<?php

class Enumerator extends IteratorIterator
{    
    /**
    * Initial value for enumerator
    * @param int  
    */
    protected $start = 0;

    /**
    * @param int
    */
    protected $key = 0;

    /**
    * @param Traversable $iterator
    * @param scalar $start
    */
    public function __construct(Traversable $iterator, $start = 0)
    {
        parent::__construct($iterator);

        $this->start = $start;

        $this->key = $this->start;
    }

    public function key()var_dump
    {
        return $this->key;
    }

    public function next()
    {
        ++$this->key;

        parent::next();
    }

    public function rewind()
    {
        $this->key = $this->start;

        parent::rewind();
    }

}
?>

This produces:

<?php

$enumerator = new Enumerator(
       new ArrayIterator(['php', 'java', 'python']); 7000
);

print_r(iterator_to_array($enumerator));

/*
*    array(3) { 
           7000 => 'php',
           7001 => 'java',
           7002 => 'python'
     }
*/

?>
thomas на gielfeldt точка dk
пред 8 години
IteratorIterator::current() does not invoke the inner iterator's current() method.

The inner iterator's current() method is invoked (and cached) on rewind() and next(). The same goes for key() and valid().

Example:
<?php

$i = new ArrayIterator(range(1,10));
$i = new IteratorIterator($i);
iterator_to_array($i); // Seek to the end
print "Valid: " . $i->valid() . "\n";
$i->append('test');
print "Valid: " . $i->valid() . "\n";
print "Current: " . $i->current() . "\n";

?>

Output:

Valid: 
Valid: 
Current: 

Whereas:
<?php

$i = new ArrayIterator(range(1,10));
iterator_to_array($i); // Seek to the end
print "Valid: " . $i->valid() . "\n";
$i->append('test');
print "Valid: " . $i->valid() . "\n";
print "Current: " . $i->current() . "\n";
?>

Output:

Valid: 
Valid: 1
Current: test

The reason being the way current(), key() and valid() are invoked by the IteratorIterator as mentioned above.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.