APP接口开发--单例模式连接数据库

<?php

class Db
{
	//拥有一个保护类实例的静态成员变量
	static private $_instance;
	static private $_connectSource;

	const HOST='mysql:host=localhost;dbname=rht-test';
	const USER='root';
	const PASS='root';
	//构造方法需要标记为非 public (防止外部使用new操作符创建对象),单例类不能在其他类中实例化,只能被自身实例化
	private function __construct()
	{

	}
	//拥有一个访问这个实例的公共静态方法
	public static function getInstance()
	{
		//判断变量是否实例化
		if(!(self::$_instance instanceof self)){
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	//防止克隆
	private function __clone()
	{
		trigger_error("Can't clone object",E_USER_ERROR);
	}

	//连接数据库
	public function connect()
	{
		self::$_connectSource = new PDO(Db::HOST,Db::USER,Db::PASS);	
		if(!self::$_connectSource){
            throw new Exception("mysql connect error");
            //die("mysql connect error".mysql_error());
        }
        self::$_connectSource->exec("set names utf8");

        return self::$_connectSource;
	}	

}

//连接数据库
$db = Db::getInstance()->connect();
// 查询数据库
$recordset = $db->query("select * from sys_role");
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetchAll();

 echo "<pre>";
 var_dump($result);
发布了40 篇原创文章 · 获赞 0 · 访问量 681

猜你喜欢

转载自blog.csdn.net/weixin_39218464/article/details/104068505