PHP Object Iteration

PHPServer Side ProgrammingProgramming

Introduction

From PHP 5 onwards, it is possible to iterate through list of all visible items of an object. Iteration can be performed using foreach loop as well as iterator interface. There is also IteratorAggregate interface in PHP, that can be used for this purpose

Using foreach loop

Example

 Live Demo

<?php
class myclass{
   private $var;
   protected $var1;
   public $x, $y, $z;
   public function __construct(){
      $this->var="private variable";
      $this->var1=TRUE;
      $this->x=100;
      $this->y=200;
      $this->z=300;
   }
   public function iterate(){
      foreach ($this as $key => $value) {
         print "$key => $value\n";
      }
   }
}
$obj = new myclass();
foreach($obj as $key => $value) {
   print "$key => $value\n";
}
echo "\n";
$obj->iterate();
?>

Output

The output is as below −

x => 100
y => 200
z => 300

var => private variable
var1 => 1
x => 100
y => 200
z => 300

Using Iterator Interface

This interfce defines following abstract methods whih will be implemnted in following example

abstract public current ( void ) : mixed
abstract public key ( void ) : scalar
abstract public next ( void ) : void
abstract public rewind ( void ) : void
abstract public valid ( void ) : bool

Iterator::current — Return the current element

Iterator::key — Return the key of the current element

Iterator::next — Move forward to next element

Iterator::rewind — Rewind the Iterator to the first element

Iterator::valid — Checks if current position is valid

Following example demonstrates object iteration by implementing Iterator interface

Example

 Live Demo

<?php
class myclass implements Iterator{
   private $arr = array('a','b','c');
   public function rewind(){
      echo "rewinding\n";
      reset($this->arr);
   }
   public function current(){
      $var = current($this->arr);
      echo "current: $var\n";
      return $var;
   }
   public function key() {
      $var = key($this->arr);
      echo "key: $var\n";
      return $var;
   }
   public function next() {
      $var = next($this->arr);
      echo "next: $var\n";
      return $var;
   }
   public function valid(){
      $key = key($this->arr);
      $var = ($key !== NULL && $key !== FALSE);
      echo "valid: $var\n";
      return $var;
   }
}
$obj = new myclass();
foreach ($obj as $k => $v) {
   print "$k: $v\n";
}
?>

Output

Above code produces following result −

rewinding
valid: 1
current: a
key: 0
0: a
next: b
valid: 1
current: b
key: 1
1: b
next: c
valid: 1
current: c
key: 2
2: c
next:
valid:
raja
Published on 18-Sep-2020 14:48:42
Advertisements