Thanks for the prompt response. My own take on this is to use explicit getters and setters, but then that is a habit from C#. However, the problem of arbitrary values was haunting me, so I decided to use the magic methods to trap them.
Here is what I have so far, any comments gratefully received. And thanks to NoDog for the improved Exception messages ;-)
/*
Allow the use of public property notation, $obj->prop
but prevent the getting of arbitrary properties
*/
public function __get($key)
{
$method = 'get' . ucfirst($key);
if (method_exists($this, $method))
{
return $this->$method();
}
else
{
throw new Exception(get_class($this) . "::$key does not exist");
}
}
/*
Allow the use of public property notation, $obj->prop
but prevent the setting of arbitrary or read-only properties
*/
public function __set($key, $val)
{
$method = 'set' . ucfirst($key);
if (method_exists($this, $method))
{
$this->$method($val);
}
elseif (property_exists($this->$key))
{
throw new Exception(get_class($this) . "::$key is read only");
}
else
{
throw new Exception(get_class($this) . "::$key does not exist");
}
}
Brad, in my OOP, all properties are encapsulated, hence the need for explicit getters and setters. To limit the scope of a var to class only I simply do not code a getter or setter.