<? 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