先说 ArrayAccess 吧!ArrayAccess 的作用是使得你的对象可以像数组一样可以被访问。应该说 ArrayAccess 在PHP5中才开始有的,PHP5中加入了很多新的特性,当然也使类的重载也加强了,PHP5 中添加了一系列接口,这些接口和实现的 Class 统称为 SPL。
ArrayAccess 这个接口定义了4个必须要实现的方法:
1 2 3 4 5 6 | { abstract public offsetExists ( $offset ) //检查偏移位置是否存在 abstract public offsetGet ( $offset ) //获取一个偏移位置的值 abstract public void offsetSet ( $offset , $value ) //设置一个偏移位置的值 abstract public void offsetUnset ( $offset ) //复位一个偏移位置的值 } |
所以我们要使用ArrayAccess这个接口,就要实现相应的方法,这几个方法不是随便写的,我们可以看一下 ArrayAccess 的原型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /** * Interface to provide accessing objects as arrays. * @link http://php.net/manual/en/class.arrayaccess.php */ interface ArrayAccess { /** * (PHP 5 >= 5.0.0)<br/> * Whether a offset exists * @link http://php.net/manual/en/arrayaccess.offsetexists.php * @param mixed $offset <p> * An offset to check for. * </p> * @return boolean true on success or false on failure. * </p> * <p> * The return value will be casted to boolean if non-boolean was returned. */ public function offsetExists( $offset ); /** * (PHP 5 >= 5.0.0)<br/> * Offset to retrieve * @link http://php.net/manual/en/arrayaccess.offsetget.php * @param mixed $offset <p> * The offset to retrieve. * </p> * @return mixed Can return all value types. */ public function offsetGet( $offset ); /** * (PHP 5 >= 5.0.0)<br/> * Offset to set * @link http://php.net/manual/en/arrayaccess.offsetset.php * @param mixed $offset <p> * The offset to assign the value to. * </p> * @param mixed $value <p> * The value to set. * </p> * @return void */ public function offsetSet( $offset , $value ); /** * (PHP 5 >= 5.0.0)<br/> * Offset to unset * @link http://php.net/manual/en/arrayaccess.offsetunset.php * @param mixed $offset <p> * The offset to unset. * </p> * @return void */ public function offsetUnset( $offset ); } |
下面我们可以写一个例子,非常简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?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 |