* 单例模式实现类-->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
)
)
**/
