
Originally Posted by
bonefry
PHP Code:
function __set($property, $value)
{
$methodName = 'set'.(strtoupper(substr($property,0,1)).substr($property,1));
if (!method_exists($this, $methodName))
throw new Exception("$property setter is not defined");
$this->$methodName($value);
}
I like it.
Remember that PHP is caseinsensitive, so you can drop the substrs:
PHP Code:
class TimeTask
{
private $_timer = null;
function __set($property, $value)
{
$method = 'set'.$property;
if (!method_exists($this, $method))
throw new Exception("$property setter is not defined");
$this->$method($value);
}
function __get($property)
{
$method = 'get'.$property;
if (!method_exists($this, $method))
throw new Exception("$property getter is not defined");
return $this->$method();
}
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;
// this will throw an exception
echo $t->unknownProperty;
And this really should be in a standard library somewhere so we can extend from it:
PHP Code:
class PObject
{
function __set($property, $value)
{
$method = 'set'.$property;
if (!method_exists($this, $method))
throw new Exception("$property setter is not defined");
$this->$method($value);
}
function __get($property)
{
$method = 'get'.$property;
if (!method_exists($this, $method))
throw new Exception("$property getter is not defined");
return $this->$method();
}
}
Perhaps it'll be in ZObject? Who to recommend it to?
Douglas
Bookmarks