Monday, October 12, 2009

Better access to properties/attributes

Iterating through an object's properties/attributes is something you can easily do with __dict__ in Python. PHP doesn't automatically give you this feature, but you can build it in via the __get and __set overloads. It requires that you follow a certain class definition pattern, but it should not be hard to add this pattern after a class is established:
class Foo {
  private $data = array();
  function __get($k) {
    return $this->data[$k];
  function __set($k, $v) {
    $this->data[$k] = $v;
  function __isset($k) {
    return isset($this->data[$k]);
  function __unset($k) {
The $data attribute acts as the object itself; __get and __set translate between object property and array entry requests. __isset and __unset handle sset() and unset() calls (only PHP 5.1.0+). Documentation can be found in the Overloading section of the PHP manual. Once you've implemented this pattern, it's trivial to access the object's attributes as an array which means that it's easy to iterate over entries.