Let's say php implements the singleton mode.

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.