返回用mysqli......登陆

用mysqli功能完成数据库连接的单例模式案例

昕旸2019-04-10 12:14:34314

//在这个作业中,完成数据库连接的单例模式,和课堂中例子的唯一区别,就是需要在类的构造函数中完成数据库的连接操作,这里使用mysqli功能完成和数据库的连接,具体代码如下

<?php

header("content-type:text/html;charset=utf-8");//开启支持中文

class DbSingleton

{

    private $charset = "utf8";         //字符串编码

//创建类的内部静态属性,保存类的唯一实例

    private static $instance = NULL;   

//关闭外部接口

    private function __construct($host, $username, $password, $dbname, $port)

    {

//mysqli方法连接数据库       

 $link = mysqli_connect($host, $username, $password, $dbname, $port);

        if (!$link) {

            die("连接错误: " . mysqli_connect_error());

        }

        // 修改数据库连接字符集为 utf8

        mysqli_set_charset($link, $this->charset);

        return $link;

    }


    //关闭clone接口

    private function __clone()

    {

    }


//创建一个外部接口,创建并返回唯一实例

    public static function getInstance($host, $username, $password, $dbname, $port)

    {

        if (is_null( static::$instance) ) ) {

            static::$instance = new static($host, $username, $password, $dbname, $port);

        }

        return static::$instance;

    }

}


//从外部实例化

$host     = '127.0.0.1';

$username = 'root';

$password = '123456';

$dbname   = 'test';

$port     = 3306;

$Db = DbSlingleton :: getInstance

($host, $username, $password, $dbname, $port);

var_dump($db);




最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送