那个单例模式做一个Db类,跟tp5 Db静态类一样的功能
<?php //单例设计模式,不能new 不能clone class Db { private $db_host;//主机名 private $db_user;//主机账号 private $db_password;//主机密码 private $db_name;//选择数据库 private $db_char;//选择字符集 private $link;//创建链接对象 private static $obj = null; private function __construct($db_host2,$db_user2,$db_password2,$db_name2,$db_char2) { $this->db_host = $db_host2; $this->db_user = $db_user2; $this->db_password = $db_password2; $this->db_name = $db_name2; $this->db_char = $db_char2; $this->connect(); $this->char(); } public function connect()//链接数据库方法 { $link2 = mysqli_connect($this->db_host,$this->db_user,$this->db_password,$this->db_name); $this->link = $link2;//$link赋值成为类的属性,就可以用了 if(!$this->link) { echo '链接错误'.mysqli_connect_error(); } } public function char()//设置字符集 { mysqli_set_charset($this->link,$this->db_char); } public function __destruct()//析构方法 { mysqli_close($this->link);//关闭链接 } private function __clone(){} public static function getInstance($db_host,$db_user,$db_password,$db_name,$db_char)//传参数进去 { if( !self::$obj instanceof self ) //关键字 instanceof 判断有没有对象 { self::$obj = new self($db_host,$db_user,$db_password,$db_name,$db_char);//new对象和传参 } return self::$obj; } } $cla = Db::getInstance('127.0.0.1','root','root','test','utf8');
这样静态调用一下就可以使用静态类了