2 min read

PHP Object Iteration

PHP provides a way for objects to be defined so it is possible to iterate through a list of items, for example with a foreach statement.


1. Simple Iteration

By default, all visible properties will be used for the iteration.

class MyClass {
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

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

$class = new MyClass();

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

$class->iterateVisible();

2. The Iterator Interface

To customize object iteration, you can implement the Iterator interface. It requires 5 methods:

  • current(): Returns the current element.
  • key(): Returns the key of the current element.
  • next(): Moves forward to next element.
  • rewind(): Rewinds the Iterator to the first element.
  • valid(): Checks if current position is valid.
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );

    public function __construct() {
        $this->position = 0;
    }

    public function rewind(): void {
        $this->position = 0;
    }

    public function current(): mixed {
        return $this->array[$this->position];
    }

    public function key(): mixed {
        return $this->position;
    }

    public function next(): void {
        ++$this->position;
    }

    public function valid(): bool {
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
}

3. IteratorAggregate

Alternatively, you can implement the IteratorAggregate interface, which requires just one method getIterator(). This is often easier if you just want to return an array iterator or a generator.

class MyCollection implements IteratorAggregate {
    private $items = [1, 2, 3];

    public function getIterator(): Traversable {
        return new ArrayIterator($this->items);
    }
}

programming/php/php programming/php/php-classes