ArrayAccess
ArrayAccess 的作用是使得你的对象可以像数组一样可以被访问。PHP5 中添加了一系列接口,这些接口和实现的 Class 统称为 SPL。
ArrayAccess 这个接口定义了4个必须要实现的方法:
{
abstract public offsetExists ($offset) //检查偏移位置是否存在
abstract public offsetGet ($offset) //获取一个偏移位置的值
abstract public void offsetSet ($offset ,$value) //设置一个偏移位置的值
abstract public void offsetUnset ($offset) //复位一个偏移位置的值
}
所以我们要使用ArrayAccess这个接口,就要实现相应的方法,这几个方法不是随便写的,我们可以看一下 ArrayAccess 的原型:
/**
* 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);
}
下面我们可以写一个例子,非常简单:
<?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