【发布时间】:2013-12-14 04:10:06
【问题描述】:
我正在创建一个 BaseModel 类,并希望使用魔术方法 __set 和 __get 而不是为每个属性定义 setter 和 getter。
我目前正在使用可变变量,因为我无法通过谷歌搜索找到另一种方法。变量变量是否被认为是不好的做法,还是我无所适从?
abstract class BaseModel implements \ArrayAccess {
/**
* Don't allow these member variables to be written by __set
*
* @var array
*/
protected $noSet = array();
/**
* Don't allow these member variables to be retrieved by __get
*
* @var array
*/
protected $noGet = array();
public function offsetExists( $offset )
{
return property_exists($this, $offset);
}
public function offsetGet( $offset )
{
return $this->__get($offset);
}
public function offsetSet( $offset , $value )
{
return $this->__set($offset, $value);
}
public function offsetUnset( $offset )
{
unset($this->$offset);
}
public function __get($member)
{
if( $member == 'noSet' || $member == 'noGet')
{
throw new \InvalidArgumentException ("Tried to access a forbidden property", 1);
}
if( ! property_exists($this, $member))
{
throw new \InvalidArgumentException ("Tried to access a non-existent property", 1);
}
if( in_array($member, $this->noGet))
{
throw new \InvalidArgumentException ("Tried to access a forbidden property", 1);
}
return $this->$member;
}
public function __set($member, $value)
{
if( $member == 'noSet' || $member == 'noGet')
{
throw new \DomainException ("Tried write to a non-writable property.", 1);
}
if( ! property_exists($this, $member))
{
throw new \InvalidArgumentException ("Tried to access a non-existent property", 1);
}
if( in_array($member, $this->noSet))
{
throw new \DomainException ("Tried write to a non-writable property.", 1);
}
return $this->$member = $value;
}
【问题讨论】:
标签: php