<?php //单例模式的实现 class MysqlInstance { private static $instance;//不可被类外部访问 private $client; private $param = array(); private function __construct() { } //实例化对象 public static function getInstance() { if (empty(self::$instance)) { self::$instance = new MysqlInstance(); } return self::$instance; } //设置连接参数 public function setClientParam($key, $value) { $this->param[$key] = $value; } //设置连接对象 public function setClient() { try { $this->client = new PDO("mysql:host=" . $this->param["server"] . ";dbname=" . $this->param["dbname"], $this->param["username"], $this->param["pwd"]); $this->client->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (\PDOException $exception) { echo $exception->getMessage(); } } //查询select public function getQuery($sql) { $re=$this->client->prepare($sql); $re->execute(); return $re->fetchAll(); } //事物查询 public function tranQuery($sql){ $t=$this->client->prepare($sql); return $t->execute(); } } //初始化 $obj = MysqlInstance::getInstance(); $obj->setClientParam("server", "127.0.0.1"); $obj->setClientParam("dbname", "test"); $obj->setClientParam("username", "root"); $obj->setClientParam("pwd", "root123"); $obj->setClient(); $re = $obj->getQuery("select * from user"); unset($obj);//删除对象后重新实例化之后对象参数依然存在 $obj2 = MysqlInstance::getInstance(); //$t=$obj2->tranQuery("insert into user (username,state) VALUES ('index',1)"); $re = $obj2->getQuery("select * from user"); var_dump($re);
在一个对象中,类的属性变量只需要设置一次,不需要进行重复的设置,如上述实现的mysql的连接的类,我们只需要进行一次连接参数设置,当引用之后的类被注销之后,再次实例化设置的参数依然存在,单例模式是对全局变量的一种改进。欢迎扫码关注微信公众号奋斗的猿类,有不足之处欢迎指正。