Implement a singleton mode: The singleton mode is a common software design pattern. In its core structure, there is only one special class that is called a singleton. The singleton mode ensures that there is only one instance of a class in the system.
The logic of the singleton mode: The class declares a static method and variable, the static variable is used to store the unique instance, the static method as the class outward unique interface, and makes the judgment inside, when the static variable has the instance time to return directly, does not have the new one instance assigns the value in the static variable inside. The constructor inside the link database operation, because the static method implemented in the control is only instantiated once, so that only link to the database once. Accessing static methods outside the class;
The simple classes are as follows:
1 classcon_db{2 Private Static $DBOBJ=NULL;3 Private $con;4 Private $result;5 Private $row;6 Private $newsItem;7 /**8 * Constructor Function9 * @param [type] $host [database address]Ten * @param [type] $username [database name] One * @param [type] $PSW [Database password] A * @param [type] $database [Database] - */ - Private function__construct ($host,$username,$PSW,$database){ the $this->con =mysql_connect($host,$username,$PSW); - if(!$this-con) { - die("Link Failed"); - } +Mysql_set_charset ("Utf-8"); - mysql_select_db($database); + } A /** at * Get Disposable objects - * @return Instance Object - */ - Public Static functionGetInstance ($host,$username,$PSW,$database){ - if(Is_null(Self::$DBOBJ)){ -Self::$DBOBJ=NewSelf$host,$username,$PSW,$database); in } - returnSelf::$DBOBJ; to } + - /** the * Database Query statements * */ $ Private functionQuery$sql){Panax Notoginseng if($sql){ - $this->result =mysql_query($sql); the if($this->result &&mysql_num_rows($this-result)) { + return $this-result; A}Else{ the return false; + } -}Else{ $ die("must fill in the query statement!")); $ } - } - /** the * Query Multiple statements - * @param $sql query StatementWuyi * return string; the */ - Private functionGetAll ($sql){ Wu $this->result =mysql_query($sql); - if($this->result &&mysql_num_rows($this-result)) { About $this->newsitem =Array(); $ while($this->row =Mysql_fetch_assoc($this-result)) { - $this->newsitem[] =$this-Row; - } - } A return $this-NewsItem; + } the /** - * Query a statement $ * @param $sql query Statement the * return string; the */ the Private functionGetOne ($sql){ the $this->result =mysql_query($sql); - if($this->result &&mysql_num_rows($this-result)) { in return $this->row =Mysql_fetch_assoc($this-result); the } the } About } the $db= Con_db::getinstance ("localhost", "root", "root", "szwengdo_com"); the $sql= "SELECT * FROM Wd_cases"; the $row=$db->getone ($sql); + Var_dump($row);
First study, hope to correct!!
PHP Singleton pattern Implementation Database class