O'Reilly logo

PHP 5 Power Programming by Derick Rethans, Stig Sæther Bakken, Andi Gutmans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required