iterate on an object

Published Feb 10, 2018

We all know an iteration over an array.
But when I see some code with an iteration over an object, I asked myself how do they do that?
Then I look up the implementation and generally what I see astound me.
There is an implementation of Iterator interface that allows looping over an object.

Here is how it works

class ClassIterator implements Iterator {
    private $datas = [];
    private $key = 0;
    public function __construct() {
          $this->datas[] = 'first item';
          $this->datas[] = 'second item';
          $this->datas[] = 'third item';
          $this->key = 0;  
    public function rewind() {
      $this->key = 0;
    public function current() {
      return $this->datas[$this->key];
    public function key() {
      return $this->key;
    public function next() {
    public function valid() {
      return isset($this->datas[$this->key]); 
    Other code 

$itObj = new ClassIterator();
foreach($itObj as $item) {
  echo  $item;

As you can see, there are five methods to implement coming from Iterator interface.
And also you can pay attention to the foreach loop iterating over the variable $itObj.
Here is the source from which you can learn more.

Discover and read more posts from Bart ehui
get started