Single-case mode of PHP design pattern (single element mode)

Source: Internet
Author: User
Tags reference return
Single case mode:

As an object's creation pattern, the singleton pattern ensures that a class has only one instance, and instantiates it and provides it globally to the entire system. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.

(1). A static member variable that holds a unique instance of the class is required: private static $_instance;

(2). Constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of a single case pattern:

Private Function __construct ()

{

$this->_db = Pg_connect (' xxxx ');

}

Private Function __clone ()

{

}

(3). You must provide a public static method (usually the GetInstance method) to access this instance to return a reference to a unique instance:

public static function getinstance ()

{

if (! (Self::$_instance instanceof Self))

{

self::$_instance = new self ();

}

return self::$_instance;



}

Why use PHP as a single case mode?

1, the application of PHP is mainly in the database application, so an application will have a large number of database operations, the use of single case mode, you can avoid a large number of new operations to consume resources.

2, if the system needs to have a class to global control of some configuration information, then the use of a single example mode can be easily implemented.




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.