ArrayAccess
简介:
是php Spl中的一个接口,提供像访问数组一样访问对象的能力。
摘要:
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 )
}
示例代码:
<?php
/**
* 实现 ArrayAccess 接口使对象可以像数组一样被访问
*/
class Configuration implements ArrayAccess
{
static private $config=null;
private $configarray = array(
'firstName' => 'kai',
'secondName' => 'xinxin',
'age' => 24
);
private function __construct(){}
public static function instance()
{
if (self::$config == null)
{
self::$config = new Configuration();
}
return self::$config;
}
/**
* [字段是否存在]
* @param [string] $index [字段名]
* @return [boolean] [字段是否存在]
*/
function offsetExists($index)
{
return isset($this->configarray[$index]);
}
/**
* [获取字段]
* @param [string] $index [字段名]
* @return [string] [字段值]
*/
function offsetGet($index) {
return $this->configarray[$index];
}
/**
* [设置字段]
* @param [string] $index [字段名]
* @param [string] $newvalue [字段值]
*/
function offsetSet($index, $newvalue) {
$this->configarray[$index] = $newvalue;
}
/**
* [删除字段]
* @param [string] $index [字段名]
*/
function offsetUnset($index) {
unset($this->configarray[$index]);
}
}
$config = Configuration::instance();
print $config["firstName"];