Single-Case mode
The three principles of the singleton pattern:
The ① constructor needs to be marked as non-public (prevents external use of the new operator from being created), and the Singleton class cannot be instantiated in other classes, but only by itself.
② has a static member variable that holds an instance of the class $_instance
③ has a public static method that accesses this instance
Singleton mode (see PHP Singleton Pattern code snippet):
<?PHP/** Single case mode*/classdb{Static Private $_instance; Private function__construct () {}Static Public functiongetinstance () {if(!self::$_instanceinstanceof Self) { Self::$_instance=NewSelf (); } returnSelf::$_instance; }}
Single-instance mode connection database:
1<?PHP2 /*3 * Single-instance mode connection database4 */5 classdb{6 Static Private $_instance;//static member variables for instances of non-public classes7 Static Private $_connectsource;//the resource handle returned by the connection database8 Private $_dbconfig=Array(9' Host ' = ' 127.0.0.1 ',Ten' Username ' = ' root ', One' pwd ' = ', A' Database ' = ' chat ' - ); - the Private function__construct () {//non-public constructors - } - - Static Public functionGetInstance () {//public static methods for accessing instances + if(!self::$_instanceinstanceof Self) { -Self::$_instance=NewSelf (); + } A returnSelf::$_instance; at } - - Public functionConnect () { - if(!self::$_connectsource){ - //Connect to MySQL service -Self::$_connectsource=mysql_connect($this->_dbconfig[' Host '],$this->_dbconfig[' username '),$this->_dbconfig[' pwd ']); in if(!self::$_connectsource){ - die(' MySQL connect error '.Mysql_error()); to } + //Select Database - mysql_select_db($this->_dbconfig[' database '],self::$_connectsource); the //Set character sets * mysql_query(' Set names ' UTF8 "', Self::$_connectsource); $ }Panax Notoginseng returnSelf::$_connectsource;//Back to Resources - } the } + A $connect= Db::getinstance ()Connect (); the Var_dump($connect); + - $sql= ' SELECT * from messages '; $ $res=mysql_query($sql,$connect); $ $num=mysql_num_rows($res); - Var_dump($num);
Page output:
Resource (3, mysql link)
int 2
PHP Development App Interface Learning notes and summary-app interface example [1]