O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

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

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

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