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‘]);
  }

 

 

PHP中的ArrayAccess讲解

上一篇:Extjs 4.2 设置buttontext为中文


下一篇:spring jdbc