PHP Design Patterns-Singleton

Source: Internet
Author: User

Overview:

     As an object's creation pattern, a singleton ensures that only one instance exists in an intrinsic system and that it cannot create a copy.
The Clone function (__clone) and the constructor (__construct) must be declared private, preventing the external program from creating a new class and losing the meaning of the singleton pattern.

The PHP language is an interpreted language, and when the page is executed, all related resources are recycled. PHP at the language level, not like the C#,java compiled language, there is no way for an object to long-distance memory.
However, in a single request scenario, it is possible to share objects through a singleton pattern, such as a database connection object.


Class dbconnection{    private static $_instance;    private static $token = 0;    public static function  getinstance ()    {        if (static::$_instance instanceof DbConnection) {            return static::$_instance;        }        Randomly produces a token indicating the current        static:: $token = rand (+);        Static::$_instance = new DbConnection ();        return static::$_instance;    }    Clone functions and constructors must be declared private,    //Prevent external programs from creating a new class, and losing the meaning of singleton patterns.    Private Function  __clone ()    {    }    Private Function  __construct ()    {    }    Public Function  Open ()    {        echo "init times:".) Static:: $token. ' <br/> ';    }}

  

Comparison of a singleton with the static class:

   1, Singleton can be very good to maintain the object's face object, such as static tool class can use static.
2, a single case can be implemented from an interface, can inherit from a class. A static class can also inherit from a class, but it is impossible to use a protect member within the parent class.


PHP Design Patterns-Singleton

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.