PHP Single State design pattern (single case mode) instance _php skill

Source: Internet
Author: User

The single state design pattern is also called a single case pattern:

1. Single State design mode meaning:

The main function of a single state pattern is to ensure that in object-oriented programming, a class can only have one instance object. As an object's creation pattern, the singleton pattern ensures that a class has only one instance, and instantiates it and provides it globally to the entire system. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.

2. Three key points for a single mode:

① requires a static member variable that holds a unique instance of the class;
② constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of the single case pattern;
③ must provide a public static method (usually the GetInstance method) to access this instance, thus returning a reference to a unique instance.

Copy Code code as follows:

<?php
Class DB {
private static $obj = null; Declares a private, static member property $obj
Private Function__construct () {//proprietary constructor method that can only instantiate an object within a class
echo "Connect the database successfully <br>";
}
The public static function getinstance () {//is not able to get objects of this class through this static method
if (Is_null (self:: $obj))//If the $obj in this class is empty, the description has not been instantiated
Self:: $obj = new self (); Instantiate the object of this class
Return self:: $obj; Returns an object of this class
}
Public Function Query ($sql) {//Execute SQL statement to complete operation of the database
Echo $sql;
}
}
$db = Db::getinstance (); Only static method getinstance () can be used to get objects of the DB class
$db-> Query ("Select *from user"); Accessing members in an object
?>

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.