7.8. Using Property Overloading
Problem
You want handler functions to execute whenever you read and write object properties. This lets you write generalized code to handle property access in your class.
Solution
Use the experimental overload extension and write _ _get( )
and _ _set( )
methods to
intercept property requests.
Discussion
Property overloading allows you to seamlessly obscure from the user the actual location of your object’s properties and the data structure you use to store them.
For example, the
pc_user
class shown in Example 7-1 stores variables in an array,
$data
.
Example 7-1. pc_user class
require_once 'DB.php'; class pc_user { var $data = array(); function pc_user($user) { /* connect to database and load information on * the user named $user into $this->data */ $dsn = 'mysql://user:password@localhost/test'; $dbh = DB::connect($dsn); if (DB::isError($dbh)) { die ($dbh->getMessage()); } $user = $dbh->quote($user); $sql = "SELECT name,email,age,gender FROM users WHERE user LIKE '$user'"; if ($data = $dbh->getAssoc($sql)) { foreach($data as $key => $value) { $this->data[$key] = $value; } } } function __get($property_name, &$property_value) { if (isset($this->data[$property_name])) { $property_value = $this->data[$property_name]; return true; } return false; } function __set($property_name, $property_value) { $this->data[$property_name] = $property_value; return true; } }
Here’s how to use the pc_user
class:
overload('pc_user'); $user = new pc_user('johnwood'); $name ...
Get PHP Cookbook 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.