31 05 2020

ArrayAccess 的作用是使得你的对象可以像数组一样可以被访问。


thinkphp/library/think/Config.php 文件

<?php
namespace think;

use Yaconf;

class Config implements \ArrayAccess
{

    ......

    // ArrayAccess
    public function offsetSet($name, $value)
    {
        $this->set($name, $value);
    }

    public function offsetExists($name)
    {
        return $this->has($name);
    }

    public function offsetUnset($name)
    {
        $this->remove($name);
    }

    public function offsetGet($name)
    {
        return $this->get($name);
    }
}


下面我们可以写一个例子


extends/ConfigObj.php

<?php

class ConfigObj implements \ArrayAccess
{

    private $config = [
      'name' => 'zwb',
      'age' => '26'
    ];

    /**
     * @inheritDoc
     * isset($config['xxx']) 对应调用offsetExists方法。
     */
    public function offsetExists($offset)
    {
        return isset($this->config[$offset]);
    }

    /**
     * @inheritDoc
     * $config['xxx'] 对应调用offsetGet方法。
     */
    public function offsetGet($offset)
    {
        return $this->config[$offset]??null;
    }

    /**
     * @inheritDoc
     * $config['xxx'] = 'yyy' 对应调用offsetSet方法。
     */
    public function offsetSet($offset, $value)
    {
        return $this->config[$offset] = $value;
    }

    /**
     * @inheritDoc
     * unset($config['xxx']) 对应调用offsetUnset方法。
     */
    public function offsetUnset($offset)
    {
        unset($this->config[$offset]);
    }
}


application/index/controller/ArrayAccessTest.php

<?php
namespace app\index\controller;

class ArrayAccessTest
{
    public function run()
    {
        $config = new \ConfigObj();
        $config['other'] = "123";  // 对应调用offsetSet方法。
        var_dump(isset($config['other']));  // 对应调用offsetExists方法。
        echo "<br/>";
        var_dump($config['other']);  // 对应调用offsetGet方法。
        echo "<br/>";
        unset($config['other']);   // 对应调用offsetGet方法。
        var_dump($config['other']);
    }
}


调试

php think run

浏览器访问:http://localhost:8000/index/ArrayAccessTest/run

输出:
bool(true)
string(3) "123"
NULL