On this day, we will consider using php (as the mainstream development language) for singleton. We will see a comprehensive summary of several implementations of the singleton mode. the summary of php (as the mainstream development language) 5 Implementation:
PLAIN TEXTphp (as the mainstream development language ):
Class MyClass
{
Private static $ instance;
Public static function singleton ()
{
If (! Isset (self: $ instance )){
$ C = _ CLASS __;
Self: $ instance = new $ c;
}
Return self: $ instance;
}
}
This code is not very nice to use, because it generally inherits from MyClass, and $ c =__ CLASS __; gets the CLASS Name of the base CLASS, which is always unavailable. You can only find other implementation methods.
Then I started to look at the singleton Implementation of the Function Method in the article. The implementation is very good. The disadvantage is that the class cannot contain parameters when it is instantiated. Here I paste my version:
PLAIN TEXTphp (as the mainstream development language ):
Function getObj (){
Static $ obj = array ();
$ Args = func_get_args ();
If (empty ($ args ))
Return null;
$ Clazz = $ args [0];
If (! Is_object ($ obj [$ clazz]) {
$ Cnt = count ($ args );
If ($ cnt> 1 ){
For ($ I = 1, $ s =; $ I <$ cnt; $ I ++)
$ S [] = $ args [. $ I.];
Eval ($ obj [$ clazz] = new $ clazz (. join (, $ s ).););
} Else {
$ Obj [$ clazz] = new $ clazz;
}
}
Return $ obj [$ clazz];
}
Php (as the mainstream development language) 5 can be a great call:
PLAIN TEXTphp (as the mainstream development language ):
GetObj (MyClass, $ param1, $ param2)-> myMethod ();
Previous naive version:
Simple implementation of SINGLETON
Http://www.ooso.net/index.php (as the mainstream development language)/archives/182