单例模式封装一个数据库调用的类

时间:2021-09-07 09:10:59
<?php
class DataBases{
    public $host;
    public $user;
    public $password;
    public $dbname;
    static private $obj = null;

    private function __construct($host,$user,$password,$dbname)
    {
        $this->host = $host;
        $this->user = $user;
        $this->password = $password;
        $this->dbname = $dbname;
    }

    static function ConnectData(){
        if(self::$obj){
            return self::$obj;
        }else{
            self::$obj = new self('127.0.0.1','root','root','mfour');
            return self::$obj;
        }
    }
}

$res = Databases::ConnectData();
print_r($res);

其实单例模式就相当于是自己调用自己,自己实例化自己!

工厂模式就相当于 房东--中介--租房者  这三者之间的关系一样,不管房东怎么变化,我只要找到中介就可以了,类似于封装,避免了一处修改,多页面修改的现象!

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------

 

案例2:

<?php
//创建一个数据库类
class Db{
    private $host;
    private $user;
    private $pwd;
    private $dbname;

    private static $db;

    //第一步:声明一个私有的构造
    private function __construct($host,$user,$pwd,$dbname)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pwd = $pwd;
        $this->dbname = $dbname;
    }

    public static function NewSelf(){
        if(self::$db){
            return self::$db;
        }else{
            self::$db = new self('127.0.0.1','root','root','monththree');
            return self::$db;
        }
    }

    //链接数据库
    public function connect(){
        $link = mysqli_connect($this->host,$this->user,$this->pwd,$this->dbname);
        mysqli_query($link,'set names utf8');
        return $link;
    }

    //封装一个入库的方法
    public function AddData(){
        //拿到link
        $link = $this->connect();
    }
}

$res = Db::NewSelf();
$link = $res->connect();
print_r($link);