* ** Singleton mode implementation class -- & amp; gt; ArrayAccess (array-based access) interface ** @ authorflyer0126 * @ since2012427 * classSingle {pr .../**
* Singleton 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 It (inherit from 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;
}
/**
* Four implementation methods
* OffsetExists (), used to identify whether an element has been defined
* OffsetGet () is used to return the value of an element.
* OffsetSet (), used to set a new value for an element
* OffsetUnset () is used to delete an element and corresponding values.
**/
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
)
)
**/