温馨提示: 这篇文章于2503天前编写,现在可能不再适用或落后.

PHP中有很多接口类,不过平时都不会怎么用到.一般访问php类的变量都是使用 类->变量名 进行访问.

除了这样还可以实现接口类用数组方式进行访问 类["变量名"]

需要实现的是ArrayAccess接口类并且实现这个接口的4个方法就可以了.

//判断存在
public function offsetExists($offset);
//获取时
public function offsetGet($offset);
//设置时
public function offsetSet($offset, $value);
//删除时
public function offsetUnset($offset);

是不是有点像php类的魔术方法呢? __get __set __unset  __isset

ArrayAccess接口具体使用方法:

class Test implements ArrayAccess {
   
   public function offsetExists($offset){
      return isset($this->$offset);
   }
   
   public function offsetGet($offset){
      return $this->$offset;
   }
   
   public function offsetSet($offset, $value){
      $this->$offset = $value;
   }
   
   public function offsetUnset($offset){
      unset($this->$offset);
   }
}

赋值判断删除获取

$obj = new Test();
$obj['a'] = '1';//设置a = 1
$obj['b'] = '2';//设置b = 2
var_dump(isset($obj['c']));//判断c
var_dump(isset($obj['a']));//判断a
unset($obj['a']);//删除a
if(isset($obj['a'])){//判断a是否存在
   var_dump($obj['a']);//获取a
}

    阁下需要登录后才可以查看评论哦~

    随便看看

      载入中...

      正在准备穿越次元,阁下请稍等片刻~