天天看点

PHP预定义接口之 ArrayAccessArrayAccess

原文地址:https://www.cnblogs.com/zyf-zhaoyafei/p/5228652.html

ArrayAccess

ArrayAccess 的作用是使得你的对象可以像数组一样可以被访问。应该说 ArrayAccess 在PHP5中才开始有的,PHP5中加入了很多新的特性,当然也使类的重载也加强了, PHP5 中添加了一系列接口,这些接口和实现的 Class 统称为 SPL。这个接口定义了4个必须要实现的方法:

{
    public function offsetExists($offset);
    public function offsetGet($offset);
    public function offsetSet($offset, $value);
    public function offsetUnset($offset);
}
           

下面是个例子:

<?php
class Test implements ArrayAccess
{
    private $testData;

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

    public function offsetSet($key, $value)
    {
        $this->testData[$key] = $value;
    }

    public function offsetGet($key)
    {
        return $this->testData[$key];
    }

    public function offsetUnset($key)
    {
        unset($this->testData[$key]);
    }
}

  $obj = new Test();

  //自动调用offsetSet方法
  $obj['data'] = 'data';

  //自动调用offsetExists
  if(isset($obj['data'])){
    echo 'has setting!';
  }
  //自动调用offsetGet
  var_dump($obj['data']);

  //自动调用offsetUnset
  unset($obj['data']);
  var_dump($test['data']);

  //输出:
  //has setting!
  //data  
  //null
           
php