码迷,mamicode.com
首页 > 数据库 > 详细

PHP单例模式实例,连接数据库对类的引用

时间:2018-10-09 12:20:20      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:min   his   cti   soc   learn   self   return   模式   连接   

<?php
//单例模式连接数据库
class pzhang{
static private $instance;
private static $config;
private $dbase = array(
‘host‘ => ‘localhost‘,
‘username‘ =>‘root‘,
‘password‘=>‘root‘,
‘dbname‘ =>‘jmyp‘
);
private function __construct(){
}
static public function getInstance(){
if(!self::$instance instanceof self)
self::$instance = new self();
return self::$instance;
}
public function conn(){
$mysql_db = $this->dbase[‘dbname‘];
self::$config = new mysqli($this->dbase[‘host‘],$this->dbase[‘username‘],$this->dbase[‘password‘]);
self::$config->query(‘set name utf8‘);
self::$config -> select_db($mysql_db);
$sql = "select * from admin";
$row = self::$config->query($sql);
$data = [];
while($tmp = $row->fetch_assoc()){
$data[] = $tmp;
}
echo "<pre>";
print_r($data);
echo "</pre>";
return self::$config;
}
}
$obj = pzhang::getInstance();
$obj->conn();

//单例模式对类的引用
class zhangp{
public function system(){
echo "learning more";
}
}

class singleCase{
static private $instance;
private $avg;
private function __construct($config){
self::$instance = new $config;
}
static public function getInstance($avg){
if(!self::$instance instanceof self)
new self($avg);
return self::$instance;
}
}
$obj = singleCase::getInstance(‘zhangp‘);
$obj->system();
?>

PHP单例模式实例,连接数据库对类的引用

标签:min   his   cti   soc   learn   self   return   模式   连接   

原文地址:https://www.cnblogs.com/isuansuan/p/9759535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!