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

Posted 酸suan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP单例模式实例,连接数据库对类的引用相关的知识,希望对你有一定的参考价值。

<?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单例模式实例,连接数据库对类的引用的主要内容,如果未能解决你的问题,请参考以下文章

PHP设计模式:单例模式

PHP常用的三种设计模式

php设计模式之单例模式

PHP单例类

php单例连接数据库

PHP开发APP接口