PHP design mode single-instance mode (single-element mode) _php Tutorial

Source: Internet
Author: User

PHP design mode singleton mode (single element mode)


Single-Case mode:

As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the whole system globally. Instead of creating an instance copy, it returns a reference to the instance stored inside the singleton class.

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

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

Private Function __construct () {$this->_db = pg_connect (' xxxx ');} Private Function __clone () {}

(3). You must provide a public static method that accesses this instance (typically the GetInstance method), which returns a reference to the unique instance:

public static function getinstance () {if (! (Self::$_instance instanceof Self)) {self::$_instance = new self ();} return self::$_instance;}

Why use PHP singleton mode?

1, the application of PHP is mainly in the database application, so there will be a large number of database operations in an application, using a singleton mode, you can avoid a large number of new operations to consume resources.

2, if the system needs to have a class to control some of the configuration information globally, then using the singleton mode can be easily implemented.


http://www.bkjia.com/PHPjc/997426.html www.bkjia.com true http://www.bkjia.com/PHPjc/997426.html techarticle PHP Design Pattern singleton mode (single element mode) Singleton mode: As an object creation mode, the singleton mode ensures that a class has only one instance, and instantiates itself and to the whole ...

  • 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.