The content of this article is about PHP’s singleton mode code, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.
Singleton mode, only one class is allowed Instantiate an object to save memory.
Up code:
<?php header("Content-Type:text/html;charset=utf8"); //定义最终的单利的数据库操作类 final class Db{ private static $obj = null; //私有的数据库配置信息 private $dbHost; private $dbName; private $dbUser; private $dbPass; private $charset; //私有的构造方法 private function __construct($conf){ $this -> dbHost = $conf['dbHost']; $this -> dbUser = $conf['dbUser']; $this -> dbName = $conf['dbName']; $this -> dbPass = $conf['dbPass']; $this -> charset = $conf['charset']; $this->connectDb(); $this->selectDb(); $this->setCharset(); } //私有的克隆方法 private function __clone(){} public static function getInstance($conf){ if(!self::$obj instanceof self){ self::$obj = new self($conf); } return self::$obj; } //私有的连接数据库方法 private function connectDb(){ if(!@mysql_connect($this->dbHost,$this->dbUser,$this->dbPass)){ die('PHP连接mysql出错'); } } //私有的选择数据库方法 private function selectDb(){ if(!mysql_select_db($this->dbName)){ die('连接数据库出错'); } } //私有的选择字符集方法 private function setCharset(){ mysql_set_charset($this->charset); } //将sql语句分为两类,返回结果集和返回布尔值 //返回布尔值 public function exec($sql){ //将sql语句转化为小写 $sql = strtolower($sql); //判断是否为select语句 if(substr($sql,0,6) == 'select'){ die('不能执行select语句'); } return mysql_query($sql); } //私有的执行select语句(结果集不能直接展示给前端,得经过处理返给对象) private function query($sql){ //将sql语句转化为小写 $sql = strtolower($sql); //判断是否为select语句 if(substr($sql,0,6) != 'select'){ die('只能执行select语句'); } return mysql_query($sql); } //将查询到的结果集返回给前端(返回一条) public function fetchOne($sql,$type=3){ $res = $this ->query($sql); $types = array( 1 => MYSQL_NUM, 2 => MYSQL_ASSOC, 3 => MYSQL_BOTH, ); //返回一条记录 return mysql_fetch_array($res,$types[$type]); } //将查询到的结果集返回给前端(返回多条) public function fetchAll($sql,$type=2){ $res = $this ->query($sql); $types = array( 1 => MYSQL_NUM, 2 => MYSQL_ASSOC, 3 => MYSQL_BOTH, ); while($row = mysql_fetch_array($res,$types[$type])){ $arr[] = $row; } return $arr; } //公共的获取记录数的方法 public function getCount($sql){ $res= $this ->query($sql); return mysql_num_rows($res); } }
Test code:
<?php header("Content-Type:text/html;charset=utf8"); //类的自动加载 spl_autoload_register(function ($className){ $arr = array( "./libs/{$className}.class.php", ); foreach($arr as $path){ if(file_exists($path)){ require_once($path); } } }); $arr = array( 'dbHost' => 'localhost', 'dbUser' => 'root', 'dbPass' => 'root', 'dbName' => 'test', 'charset' => 'utf8', ); $db = Db::getInstance($arr); $sql = "select * from account where id = 100;"; var_dump($db->fetchOne($sql,2));
The above is the detailed content of PHP singleton pattern code. For more information, please follow other related articles on the PHP Chinese website!