/**
* 單例模式實作類別-->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
)
)
**/