by Dinesh Thakur

The conditional structure "foreach" when you allowed to browse the contents of a table. With version 5 of PHP, you can now browse an entire object to retrieve its properties.

Reminder of Interfaces

An interface is a way to contract with a class, to ensure that it will have much of certain methods / properties. Unlike inheritance, it is possible to implement multiple interfaces, allowing to overcome the inability to use multiple inheritance in PHP.

The Iterator interface

The native interface Iterator has existed for some time in Java and provides a significant advantage in terms of object oriented programming. Here's what the code looks like the Iterator interface:

<?php
    Interface Iterator
   {
        public function rewind();
        public function key();
        public function current();
        public function next();
        public function valid();
    }
?>

Browse an object with foreach ()

<?php
    class MyClass {
        protected $arg1 = 'Good' ;
        protected $arg2 = 'Bye';
         //...
     }
      $c = new MyClass();
      foreach($c as $key=>$value) {
      echo $key, ' : ', $value, '<br/>';
   }
?>

This will print:

arg1 : Good
arg2 : Bye

This is where the Iterator interface. She will indeed help you customize the behavior of foreach. Implement this interface in your class requires you to overload (or redefine) the following 5 methods: rewind (), next (), key (), current () and valid ().

<?php
    class MyClass implements Iterator {
      protected $n;
      const MAX = 5;

      public function rewind() {
          $this->n = 0;
       }

      public function next() {
           $this->n++;
       }

       public function key() {
           return 'increment '.$this->n+1;
       }

      public function current() {
           return $this->n;
       }

       public function valid() {
            return $this->n<=self::MAX;
       }
}
      $c = new MyClass();
         foreach($c as $key => $val) {
           echo $key,' : ',$val, '<br/>';
        }
?>

This will print:

increment 1: 0
increment 2: 1
Increment 3: 2
increment 4: 3
increment 5: 4

These methods will be called by foreach, in this order:

1. rewind at the first iteration, which allows you to rewind your item (here it gives $ n 0)
2. valid which verifies that one does not arrive at the end of the iteration (where $ n is less than the maximum number of iterations set by the constant MAX). If valid returns TRUE, if it continues we stop, it's the end of the iteration.
3. which returns the current value of the current iteration (here $ n)
4. key which returns the key of the current iteration (here key. $ n)
5. next that starts the next iteration (here, $ n is incremented by 1)
6. Is recalled after the valid () method that checks again that we did not come under Iteration.

Note [1]: A class can not implement two interfaces that share, however, function names.