Skip to content
PHP Logo

When should the Iterator and Countable interfaces be implemented in PHP classes?

The Iterator interface should be implemented in PHP classes when you want to iterate over the object's properties using a foreach loop. The Countable interface should be implemented when you want to use the count() function on an object to get the number of elements it contains. By implementing these interfaces, you can make your classes more versatile and compatible with standard PHP functions.

php
class MyIterator implements Iterator, Countable {
    private $data = [];
    
    public function __construct(array $data) {
        $this->data = $data;
    }
    
    public function current() {
        return current($this->data);
    }
    
    public function key() {
        return key($this->data);
    }
    
    public function next() {
        next($this->data);
    }
    
    public function rewind() {
        reset($this->data);
    }
    
    public function valid() {
        return key($this->data) !== null;
    }
    
    public function count() {
        return count($this->data);
    }
}

$data = [1, 2, 3, 4, 5];
$iterator = new MyIterator($data);

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

echo "Count: " . count($iterator);