/**
* Single-instance mode implementation class-->arrayaccess (array access) interface
*
* @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
Adjust (Inherit arrayaccess && implement 4 methods)
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;
}
/**
* Implementation of four methods
* Offsetexists (), used to identify whether an element is defined
* Offsetget (), used to return the value of an element
* Offsetset (), used to set a new value for a single element
* Offsetunset (), used to delete an element and the corresponding value
**/
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
)
)
**/