一般来说,类具有属性和方法,我们把属性对应于类的成员变量,其中成员变量是相对于类内部而言的,对于使用这个类的人来说,我们看到的是类的属性。所以嘞,我们就可以通过setter和getter的方式,把一个类中的方法作为类的属性供外部使用。例如:
class AAA extends BaseObject
{
public function setPro1()
{}
pubic function getPro1()
{}
}
$a = new AAA();
我们就可以使用$a->pro1 = 'aaa', var_dump($a->pro1)来设置和获取属性pro1。
1.通过重写__set魔术方法,实现setter,代码如下:
public function __set($name, $value)
{
$setter = 'set'.ucfirst($name);
$getter = 'get'.ucfirst($name);
if (method_exists($this, $setter)) {
return $this->$setter($value);
} else if (method_exists($this, $getter)) {
throw new Exception('read-only property!');
} else {
throw new Exception('unknown property!');
}
}
2.通过重写__get魔术方法,实现getter,代码如下:
public function __get($name)
{
$setter = 'set'.ucfirst($name);
$getter = 'get'.ucfirst($name);
if (method_exists($this, $getter)) {
return $this->$getter();
} else if (method_exists($this, $setter)) {
throw new Exception('write-only property!');
} else {
throw new Exception('unknown property!');
}
}
最后我们还要考虑到,isset()和unset()的问题,所以要重写__isset和__unset魔术方法,代码如下:
public function __isset($name)
{
$getter = 'get'.ucfirst($name);
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
} else {
return false;
}
}
public function __unset($name)
{
$setter = 'set'.ucfirst($name);
$getter = 'get'.ucfirst($name);
if (method_exists($this, $setter)) {
return $this->$setter(null);
} else if (method_exists($this, $getter)) {
throw new Exception('read-only property!');
}
}
ok,今儿个先到这,欲知下事如何,且听下回分解……
github源码:https://github.com/2lovecode/tank