PHP Single-instance mode

Source: Internet
Author: User

In the actual development, the use of a single example mode with a lot of, such as linked database operations, log processing classes and other operations can be used in a single case mode.

Singleton mode is actually a class can only have an instance of a class, then how to achieve this effect? We need to meet 3 conditions when writing a class to achieve a single-mode effect:

The constructor must be declared as a non-public type, so that no other place can produce an instance by new, which also avoids the generation of instances of multiple classes

A static member variable, such as $_instance, that can hold an instance of a class is required in a class.

Having a public static method that accesses this instance, such as getinstance ();

<?phpclass Test {static private $_instance;private function __construct () {}static public Function getinstance () {if (! (Self::$_instance instanceof Self)) {self::$_instance = new self ();} return self::$_instance;}}


This article is from the "Wang Xinhua" blog, make sure to keep this source http://singwa.blog.51cto.com/3086810/1534151

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.