title: PHP interfaces IteratorAggregate vs Iterator?
body: <p>The <code>IteratorAggregate</code> is an <em>interface to create an external Iterator</em>:</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>class myData implements IteratorAggregate
  {
      public $property1 = "Public property one";
      public $property2 = "Public property two";
      public $property3 = "Public property three";
  
      public function __construct()
      {
          $this-&gt;property4 = "last property";
      }
  
      public function getIterator()
      {
          return new ArrayIterator($this);
      }
  }
  
  $obj = new myData;
  </code></pre>
  
  <p>And you'll be able to traverse the object using <code>foreach</code>:</p>
  
  <pre class="lang-php prettyprint-override"><code>foreach($obj as $key =&gt; $value) {
      var_dump($key, $value);
      echo "\n";
  }
  </code></pre>
  
  <p>While <code>Iterator</code> is an <em>interface for external iterators or objects that can be iterated themselves internally</em>:</p>
  
  <pre class="lang-php prettyprint-override"><code>class myIterator implements Iterator
  {
      private $position = 0;
      private $array = array('one', 'two', 'three');
  
      function rewind()
      {
          $this-&gt;position = 0;
      }
  
      function current()
      {
          return $this-&gt;array[$this-&gt;position];
      }
  
      function key()
      {
          return $this-&gt;position;
      }
  
      function next()
      {
          ++$this-&gt;position;
      }
  
      function valid()
      {
          return isset($this-&gt;array[$this-&gt;position]);
      }
  }
  </code></pre>
  
  <p>And again, you can traverse it basically the same way:</p>
  
  <pre class="lang-php prettyprint-override"><code>$it = new myIterator;
  
  foreach($it as $key =&gt; $value) {
      var_dump($key, $value);
      echo "\n";
  }
  </code></pre>
  
  <p>So can anyone explain why we need two interfaces and what's the difference between them?</p>