Let's talk about how to implement the singleton mode in php and whether to implement the singleton mode in php. On this day, we will consider using php for singleton. we will see a comprehensive summary of several implementations of the singleton mode. the summary of the php5 implementation: PLAINTEXTPHP: classMyClass {privatestatic $ instan
On this day, we will consider using php for singleton. we will see a comprehensive summary of several implementations of the singleton mode, which summarizes the implementation of php5:
Plain textphp:
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:
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];
}
In php5, you can easily call:
Plain textphp:
GetObj ('myclass', $ param1, $ param2)-> myMethod ();
Previous naive version:
Simple implementation of SINGLETON
Http://www.ooso.net/index.php/archives/182