手撸php框架4.2--构建BaseObject之setter,getter实现

本文介绍如何利用PHP的魔术方法__set、__get、__isset和__unset实现类属性的动态setter和getter方法,并通过示例代码展示其用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般来说,类具有属性和方法,我们把属性对应于类的成员变量,其中成员变量是相对于类内部而言的,对于使用这个类的人来说,我们看到的是类的属性。所以嘞,我们就可以通过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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值