php 接口 ArrayAccess 实例:实现属性或数组的方式访问类成员变量

php 的 ArrayAccess 接口可以实现以数组下标的方式访问类的成员属性,我们只需要实现此接口的四个抽象方法即可

public function offsetSet($index, $val);

public function offsetGet($index);

public function offsetExists($index);

public function offsetUnset($index);

不过看了不少博文都是直接让类变成了彻底的数组下标访问模式,有种忘本逐末的赶脚,其并不烦,我们在实现此接口的同时用几个魔术函数就能完美实现。

<?php
/**
 * 实现使用数组键值的方式访问对象属性
 */
class Foo implements ArrayAccess
{
    private static $_instance;

    //成员属性数组
    private $_members;

    private function __construct()
    {
        //not allow to call construct operation from outer
    }

    /**
     * 单例模式
     * @return instance of Foo Class
     */
    public static function getInstance()
    {
        if ( isset(static::$_instance) ) {
            return static::$_instance;
        }

        return static::$_instance = new static();
    }

    //对应 offsetSet
    public function __set($index, $val)
    {
        $this->_members[$index] = $val;
    }

    //对应 offsetGet
    public function __get($index)
    {
        return isset($this->_members[$index]) ? $this->_members[$index] : null;
    }

    //对应 offsetExists
    public function __isset($index)
    {
        return isset($this->_members[$index]);
    }

    //对应 offsetUnset
    public function __unset($index)
    {
        if ( isset($this->_members[$index]) ) {
            unset($this->_members[$index]);
        } else { // 属性不存在
            trigger_error($index . " not exits!", E_USER_WARNING);
        }
    }

    public function offsetSet($index, $val)
    {
        $this->_members[$index] = $val;
    }

    public function offsetGet($index)
    {
        return isset($this->_members[$index]) ? $this->_members[$index] : null;
    }

    public function offsetExists($index)
    {
        return isset($this->_members[$index]);
    }

    public function offsetUnset($index)
    {
        if ( isset($this->_members[$index]) ) {
            unset($this->_members[$index]);
        } else {
            trigger_error($index . " not exits!", E_USER_WARNING);
        }
    }
}

$bar = Foo::getInstance();

$bar->name = "sallency";

echo $bar['name'] . PHP_EOL;

$bar['name']  = "big_cat";

echo $bar->name . PHP_EOL;

其实就是利用魔术方法和接口的方法将他们对应的操作都定向到存放属性的成员数组中去

转载于:https://my.oschina.net/sallency/blog/837639

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值