PHP 8.5.0 Alpha 2 available for testing

Voting

: eight plus one?
(Example: nine)

The Note You're Voting On

wallacemaxters at gmail dot lcom
9 years ago
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'
}
*/

?>

<< Back to user notes page

To Top