php封装MySQL的单例连接数据库
php封装MySQL的单例连接数据库代码如下:
<?php
//封装MySQL单例
class MySQLDB {
private $host; //主机地址
private $port; //端口号
private $user; //用户名
private $pwd; //密码
private $dbname; //数据接名
private $charset; //字符集
private $link; //连接对象
private static $instance;
private function __construct($param) {
$this->initParam($param);
$this->initConnect();
}
private function __clone() {
}
//获取单例
public static function getInstance($param=array()) {
if(!self::$instance instanceof self)
self::$instance=new self($param);
return self::$instance;
}
//初始化参数
private function initParam($param) {
$this->host=$param['host']??'127.0.0.1';
$this->port=$param['port']??'3306';
$this->user=$param['user']??'';
$this->pwd=$param['pwd']??'';
$this->dbname=$param['dbname']??'';
$this->charset=$param['charset']??'utf8';
}
//连接数据库
private function initConnect() {
$this->link=@mysqli_connect($this->host,$this->user,$this->pwd,$this->dbname);
if(mysqli_connect_error()){
echo '数据库连接失败<br>';
echo '错误信息:'.mysqli_connect_error(),'<br>';
echo '错误码:'.mysqli_connect_errno(),'<br>';
exit;
}
mysqli_set_charset($this->link,$this->charset);
}
}
//测试
//配置参数
$param=array(
'user' => 'root',
'pwd' => 'root',
'dbname' => 'data'
);
//获取单例
$db=MySQLDB::getInstance($param);
var_dump($db);
数据库是否链接成功打印下,var_dump($db);
页:
[1]