PHP Single-instance mode

Source: Internet
Author: User

First, what is a singleton mode?

A class can have an instance object that, when instantiated automatically, provides this instance object to the entire system

Second, what is the role?

Use the same instance object, not new, to reduce system resource waste

Three, what is the characteristic?

Class "Disallow inheritance" for final identity

Private constructor "prevent out-of-class instantiation"

Private cloning method "forbidden to be cloned"

Private static Property "Save instance object of Class"

public static function "calling interface of Class"

Purpose of the above behavior: to prevent the program from re-instantiating "consuming new resources"

Iv. Application Scenarios

Commonly used database operation class, every time using the database pants Operation class to new one object, for the system and memory resources waste is huge, and every new one to connect with the database, then the database connection number will run out quickly

V. Examples

<?PHPFinal classsingle{Private $rand= 0; //Storing instantiated objects    Static Private $obj=NULL; //prevent out-of-class instantiation    Private function__construct () {return $this-Rand=Mt_rand(1,99999); }    //calling the interface of a class    Static   Public functionUSB () {if(!self::$obj) { self::$obj=NewSingle (); }        returnSelf::$obj; }     Public functionFFF () {Echo $this-Rand; }    //prevent user cloning    Private function__clone () {Echo' Forbid cloning! ‘; }}$single 1= Single::USB ();$single 2= Single::USB ();Print_r($single 1);Print_r($single 2);$single 2-FFF (); 

PHP Single-instance mode

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.