天天看點

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