PHP中的ArrayAccess用法

最近看laravel源码,发现里面用了很多框架类实现了ArrayAccess接口,以前对这块不是很熟悉,查了一下这个语法的用法,发现这个其实就是实现让对象以数组形式来使用。

在官方文档上:

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}

实现上面的方法,下面举个实例

<?php
/**
 * Created by PhpStorm.
 * User: wangHan
 * Date: 2016/10/21
 * Time: 14:07
 */
class Human implements ArrayAccess
{
    private $elements;

    public function __construct()
    {
        $this->elements = [
            "boy" => "male",
            "girl" => "female"
        ];
    }

    public function offsetExists($offset)
    {
        // TODO: Implement offsetExists() method.
        return isset($this->elements[$offset]);
    }

    public function offsetGet($offset)
    {
        // TODO: Implement offsetGet() method.
        return $this->elements[$offset];
    }

    public function offsetSet($offset, $value)
    {
        // TODO: Implement offsetSet() method.
        $this->elements[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        // TODO: Implement offsetUnset() method.
        unset($this->elements[$offset]);
    }
}

$human = new Human();
$human['people'] = "boyAndGirl"; 自动调用offsetSet
if(isset($human['people'])) {   自动调用offsetExists
    echo $human['boy'];//自动调用offsetGet
    echo '<br />';
    unset($human['boy']);//自动调用offsetUnset
    var_dump($human['boy']);
}
// // 输出结果  male   null

引申下,配合单例使用才好!可以在自己的框架中使用。如下

<?php
//Configuration Class
class Configuration implements ArrayAccess { 

    static private $config;
    private $configarray;

    private function __construct() {
        $this->configarray = array(
            "Wang" => "Male",
            "Han" => "Female"
        );
    }

    public static function instance() {
        if (self::$config == null) {
            self::$config = new Configuration();
        }
        return self::$config;
    }

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

    function offsetGet($index) {
        return $this->configarray[$index];
    } 

    function offsetSet($index, $newvalue) {
        $this->configarray[$index] = $newvalue;
    } 

    function offsetUnset($index) {
        unset($this->configarray[$index]);
    }
} 

$config = Configuration::instance();
print $config["Wang"];
//正如你所预料的,程序的输出是"Male"。
//假如我们做下面那样的动作:
$config = Configuration::instance();
print $config["Han"];
$config['Han'] = "Wang's Lover";
// config 
$configTest = Configuration::instance();
print $configTest ['Han']; //是的,也正如预料的,输出的将是Wang's Lover
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值