Rumah >pembangunan bahagian belakang >tutorial php >ArrayAccess 创建一个类数组对象
/**
* 单例模式实现类-->ArrayAccess(数组式访问)接口
*
* @author flyer0126
* @since 2012/4/27
*/
class Single{
private $name;
private static $_Instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_Instance)
{
self::$_Instance = new Single();
}
return self::$_Instance;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$s = Single::load();
$s->setName("jack");
echo $s->getName(); //jack
// 调整一下(继承ArrayAccess && 实现4个方法)
class Single implements ArrayAccess
{
private $name;
private static $_Instance = null;
private function __construct()
{
}
static function load()
{
if(null == self::$_Instance)
{
self::$_Instance = new Single();
}
return self::$_Instance;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
/**
* 实现四个方法
* offsetExists(),用于标识一个元素是否已定义
* offsetGet(),用于返回一个元素的值
* offsetSet(),用于为一个元素设置新值
* offsetUnset(),用于删除一个元素和相应的值
**/
public function offsetSet($offset, $value)
{
if (is_null($offset))
{
$this->container[] = $value;
}
else
{
$this->container[$offset] = $value;
}
}
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
}
$s = Single::load();
$s->setName("jack");
$s["name"] = "mike";
echo $s->getName(); //jack
echo $s["name"]; //mike
print_r($s);
/**
Single Object
(
[name:Single:private] => jack
[container] => Array
(
[name] => mike
)
)
**/