Use the new features of PHP5.3 to implement the Singleton mode _ PHP Tutorial

Source: Internet
Author: User
Use the new features of PHP5.3 to implement the Singleton mode. 5.3 can also be implemented before, but the code is cumbersome, as follows: classMOrderextendsSModel {protectedstatic $ handle; example handle privatefunction _ construct () {something} *** can also be implemented before obtaining this class 5.3, but the code is cumbersome, as shown below:

Class MOrder extends SModel {
Protected static $ handle; // example handle

Private function _ construct (){
// Something
}

/**
* Obtain the method of this type of Singleton and publish it to the public.
*
* @ Return MOrder
*/
Public static function instance (){
If (self ::$ handle ){
Return self: $ handle;
}

$ Class = _ CLASS __;
Self: $ handle = new $ class ();
Return self: $ handle;
}

// Otherthing

}


5.3 added delayed static binding (this word is really awkward)

The code implementation is as follows:

Class SModel {
/**
* Gets the example handle and returns the instance objects of a specific model class.
*/
Protected static function instance (){
If (static ::$ handle ){
Return static: $ handle;
}

$ Class = get_called_class ();
Static: $ handle = new $ class ();
Return static: $ handle;
}

// Parent something

}


Class MGoods extends SModel {
/**
* Obtain the method of this type of Singleton and publish it to the public.
* @ Return MGoods
*/
Public static function instance (){
Return parent: instance ();
}
Protected static $ handle; // example handle
Protected function _ construct (){
// Something
}

// Otherthing

}


Through modification, the implementation code of the subclass is reduced by a part, which is implemented by the parent class.

To be honest, it is still very troublesome. If PHP implements singleton by itself.


Class MOrder extends SModel {protected static $ handle; // example handle private function _ construct () {// something}/*** get this class...

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.