Redefining Class Iteration

By default, when you iterate over an object, PHP serves up all of the object’s properties. That’s great for debugging, but it isn’t what you want in every situation.

For example, you’ve mapped all property accesses in your class though the special _ _get( ) and _ _set( ) methods. In this implementation, you’re storing all the data in a protected array named $data. It’s logical that when someone iterates over the class, they’re served up another element of $data. However, as things stand now, not only would they see other variables, but they’re not going to see $data, because it’s protected.

Fortunately, PHP 5 gives you the ability to control which items should appear during iteration. This lets you refine the default behavior to what’s appropriate for the class.

Before getting into the specifics, here’s a Person class for the later examples:

class Person {
    protected $data;

    public function _ _construct($firstname, $lastname) {
        $this->firstname = $firstname;  
        $this->lastname = $lastname;
    }
    
    public function _ _get($p) {
        if (isset($this->data[$p])) {
            return $this->data[$p]; 
        } else {
            return false;
        }
    }
    
    public function _ _set($p, $v) {
        $this->data[$p] = $v;
    }
    
    public function _ _toString( ) {
        return "$this->firstname $this->lastname";
    }
}

The Person class has a constructor that stores the person’s firstname and lastname. Since property access has been overridden by _ _get( ) and _ _set( ), $this->firstname really references $this->data['firstname'].

There’s also a ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.