Php design pattern Singleton pattern (single element pattern)

Source: Internet
Author: User

Php design pattern Singleton pattern (single element pattern)
Singleton mode:

 

As the object creation mode, the singleton mode ensures that a class has only one instance, and the instance is self-instantiated and global to the entire system. It does not create instance copies, but returns a reference to the instance stored in the singleton class.

 

(1). You need a static member variable that saves the unique instance of the class: private static $ _ instance;

 

(2) constructor and clone functions must be declared private to prevent external programs from losing the meaning of Singleton mode due to new classes:

Private function _ construct () {$ this-> _ db = pg_connect ('xxx');} private function _ clone (){}

(3) You must provide a public static method (usually the getInstance method) to access the instance and return a reference of a unique instance:

Public static function getInstance () {if (! (Self: $ _ instance instanceof self) {self: $ _ instance = new self ();} return self ::$ _ instance ;}

 

 

 

Why use the PHP Singleton mode?

 

1. php applications mainly lie in database applications. Therefore, a large number of database operations exist in an application. Using the singleton mode can avoid the resources consumed by a large number of new operations.

 

2. If you need a class in the system to globally control some configuration information, you can use the singleton mode to conveniently implement it.

 


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.