时间:2021-07-01 10:21:17 帮助过:2人阅读
单例模式,一个类只允许实例化一个对象,节约内存。
上代码:
<?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); } }
测试代码:
<?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));
以上就是PHP的单例模式代码的详细内容,更多请关注Gxl网其它相关文章!