实现该接口后,可以像访问数组一样访问对象。
接口摘要:
ArrayAccess
{
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}
实现该接口的对象实际是在对象内部提供了一个数组用于保存对象的各个成员属性。在外部以数组形式访问对象属性时,会自动触发对应的接口方法进行后续操作。
class TestObject implements ArrayAccess
{
// 提供一个数组用于保存成员属性
private $container = [];
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetGet($offset)
{
return isset($this->container[$offset])? $this->container[$offset] : null;
}
public function offsetSet($offset, $value)
{
if(is_null($offset))
{
$this->container[] = $value;
}else
{
$this->container[$offset] = $value;
}
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
}
$obj = new TestObject();
// 触发offsetSet
$obj['name'] = 'PHP';
// 触发offsetGet,输出PHP
var_dump($obj['name']);
// 触发offsetExists,输出true
var_dump(isset($obj['name']));
// 触发offsetUnset
unset($obj['name']);
// 触发offsetGet,输出NULL
var_dump($obj['name']);