Итератор по свойствам и методам класса


=== Итератор по открытым свойствам и методам класса ===

// Неявный итератор
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';

    protected $protected = 'Protected var';
    private   $private   = 'Private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:n";
       foreach($this as $key => $value) {
           print "$key => $valuen";
       }
    }
}
$cls = new MyClass();

foreach($cls as $key => $value) {
    print "$key => $valuen";
}
echo "n";

$cls->iterateVisible();


=== Итератор по всем свойствам и методам класса ===

// Явная реализация итератора
class MyIterator implements Iterator
{
    private $var = array();
    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }
    public function rewind() {
        echo "rewindingn";
        reset($this->var);
    }
    public function current() {
        $var = current($this->var);
        echo "current: $varn";
        return $var;
    }
    public function key() {
        $var = key($this->var);
        echo "key: $varn";
        return $var;
    }
    public function next() {
        $var = next($this->var);
        echo "next: $varn";
        return $var;
    }
    public function valid() {
        $var = $this->current() !== false;
        echo "valid: {$var}n";
        return $var;
    }
}

$it = new MyIterator($cls);
foreach ($it as $a => $b) {
    print "$a: $bn";
}

=== Итератор по коллекции ===

// Коллекция, возвращающая итератор
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this->items);
    }
    public function add($value) {
        $this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach ($coll as $key => $val) {
    echo "key/value: [$key -> $val]nn";
}