4.3. Iterators

The properties of an object can be iterated using the foreach() loop:

class MyClass {
    public $name = "John";
    public $sex = "male";
}

$obj = new MyClass();

foreach ($obj as $key => $value) {
    print "obj[$key] = $value\n";
}
Running this script results in
obj[name] = John
obj[sex] = male

However, often when you write object-oriented code, your classes don't necessarily represent a simple key/value array as in the previous example, but represent more complex data, such as a database query or a configuration file.

PHP 5 allows you to overload the behavior of the foreach() iteration from within your code so you can have it do what makes sense in respect to your class's design.

Note

Not only does PHP 5 enable you to overload this behavior, ...

Get PHP 5 Power Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.