The Person Class

The next step is creating Person, an object representation of the data. This class encapsulates the address book entry’s information into an object you can manipulate. You need to be able to create a new object, get and set information, cycle through all the fields, and convert the object to XML.

Constructor

The class begins with its constructor, as shown in Example 10-2.

Example 10-2. Person::_ _construct( )

class Person implements IteratorAggregate {
    private $data;

    public function _ _construct($person = NULL) {
        $this->data = array('firstname' => '', 
                            'lastname'  => '',
                            'email'     => '',
                            'id'        =>  0);

        if (is_array($person)) {
            foreach ($person as $field => $value) {
                $this->$field = $value;
            }
        }
    }

Example 10-2 initializes the $data property as an array of four elements: firstname, lastname, email, and id. The first three hold information about a person, and the last one is the record’s unique database key.

When nothing’s passed into the constructor, you’re left with an empty Person object, which can then be defined. However, you can optionally pass an array of data that contains information about a person.

When this happens, the constructor loops through the array and converts each element into an object property. As you’ll see, this class actually overloads property access with _ _get( ) and _ _set( ), so the information is really going inside $data.

You’ve probably noticed that none of the properties are set by name. For example, there’s no call to $this->firstname ...

Get Upgrading to PHP 5 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.