
Originally Posted by
arborint
In PHP5 you can almost pull off $obj->key = $value or $obj->setKey($value), but because the __set() and __call() functions are error handlers and not true property handlers you still have the problem with already defined properties. Hopefully PHP6 will add true property handlers.
Not really true. In fact the current setter/getter system in PHP5 is quite flexible and I like it.
PHP Code:
class TimeTask
{
private $_timer = null;
function __set($property, $value)
{
try {
$method = new ReflectionMethod(get_class($this), 'set'.(strtoupper(substr($property,0,1)).substr($property,1)));
$method->invoke($this, $value);
}
catch (ReflectionException $e) {
throw new Exception("$property setter is not defined");
}
}
function __get($property)
{
try {
$method = new ReflectionMethod(get_class($this), 'get'.(strtoupper(substr($property,0,1)).substr($property,1)));
return $method->invoke($this);
}
catch (ReflectionException $e) {
throw new Exception("$property getter is not defined");
}
}
function setTimer($value)
{
$value = (int)$value;
if ($value <= time())
throw new Exception("Cannot set time in the past");
$this->_timer = $value;
}
function getMysqlDateTime()
{
return date('Y-m-d H:i:s', $this->_timer);
}
}
$t = new TimeTask();
$t->timer = time() + 10;
echo $t->mysqlDateTime;
echo $t->unknownProperty;
Bookmarks