PHP中的ArrayAccess讲解

通过类实现四个方法:offsetExists,offsetGet,offsetSet,offsetUnset

class ObjArray implements \ArrayAccess
{
  private $testData = [
    "title" => "abc",
  ];
  public function offsetExists($key)
  {
    echo "offsetExists".$key;
    return isset($this->testData[$key]);
  }
  public function offsetGet($key)
  {
    echo "offsetGet01".$key;
    return $this->testData[$key];
  }
  public function offsetSet($key, $value)
  {
    echo "offsetSet".$key;
    $this->testData[$key] = $value;
  }
  public function offsetUnset($key)
  {
    echo "offsetUnset".$key;
    unset($this->testData[$key]);
  }
}

  调用ObjArray,如果没有实现\ArrayAccess,如下调用类,就会报错

  public function obj(){
    $obj = new \ObjArray();
    var_dump($obj['title']);
  }

 

 

posted @ 2020-08-26 11:51  爱搬砖的小码农  阅读(339)  评论(0编辑  收藏  举报