PHP设计模式---单例模式

单例模式是PHP开发中最常用的一种模式之一了.

举个例子:当使用TP5或者laravel5等框架开发网站时,可能需要实例化多个model,每个model都要去操作数据库,

如果没有单例模式,那么岂不是每个model都要去创建一个数据库请求? 这样会带来非常大的开销,本文就以Db类浅析单例模式

单例模式的设计准则:

1.构造函数设为私有,不让外部产生对象

2.拥有一个保存自己的内部静态实例

3.拥有一个提供给外部的静态函数,返回单例对象

简单说就是:不让进大门,留后门的想法.

<?php
class Db
{
    static private $_instance;  //使用_instance命名
    private $config = [
        'host'=>'localhost',
        'db'=>'test', //选择数据库
        'user'=>'root',
        'password'=>'123456'
    ];

    private function __construct(){
        //禁止外部使用构造函数
        $dsn = "mysql:host=".$this->config['host'].";dbname=".$this->config['db'];
        $user = $this->config['user'];
        $password = $this->config['password'];
        self::$_instance = new PDO($dsn,$user,$password);

    }
    private function __clone(){
        //禁止外部克隆对象
    }
    static public function getInstance(){ //使用getInstance命名

        empty(self::$_instance) && new self();
        return self::$_instance;
    }
}

$db1 = Db::getInstance();
$db2 = Db::getInstance();
var_dump($db1===$db2);

输出:true

原文地址:https://www.cnblogs.com/dpdp/p/7474742.html