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'] ...
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.