Tuesday, March 2, 2010

Dynamically adding properties in PHP :: Base Object :: Part 2

I promised in my previous article that I will not talk about the obvious in PHP. However, this one deserves mentioning, since we will be building on top of it as we go along.

Add this to our class Object that we have started in the Part 1 of this article.
All it does - it makes our object property-extensible.

protected $_aProperties = array();
...
public function __get($sProperty) {
    return isset($this->_aProperties[$sProperty]) 
        ? $this->_aProperties[$sProperty] 
        : null;
}
public function __set($sProperty, $mValue) {
    $this->_aProperties[$sProperty] = $mValue;
    return $mValue; 
}

Now you can set properties dynamically, like so:

$oMyObject->non_existing_property = 6;
print $oMyObject->non_existing_property; // outputs: 6

1 comment: