Example of a single-state design mode connection database

Source: Internet
Author: User

<? PHP
Class DB //sets the classes to final and prevents other classes from inheriting it

classdb{Private Static $obj=NULL;//declares a private, static member property $obj Private function__construct () {//Private constructor method that instantiates an object only inside the class Echo"Connect to Database Success <br>"; } Public Static functiongetinstance () {//This static method is used to get objects of this class if(Is_null(Self::$obj) )//if the $obj in this class is empty, the description has not yet been instantiated{ Self::$obj=NewSelf ();//instantiate this class of objects } returnSelf::$obj;//returns the object of this class } Public functionQuery$sql) { //Execute SQL statement to complete operations on the database Echo $sql; }}$db= Db::getinstance ();//You can only use the static method getinstance () to get the DB Class object$dbQuery ("Select *from user");//accessing members in an object?>
The single-state design mode is also called a singleton mode: 1. single-state design mode meaning: The primary function of the single-state mode is to ensure that a class can have only one instance object in the object-oriented programming design. 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. 2. three key points for single mode: ① requires a static member variable that holds a unique instance of the class, and the ② constructor and the clone function must be declared private to prevent the external program new class from losing the meaning of the singleton pattern ③ must provide a common static method that accesses this instance (typically the GetInstance method), which returns a reference to the unique instance. 

Example of a single-state design mode connection database

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.