Home > Article > Backend Development > One trick to solve PHP singleton pattern analysis and practical combat
We have learned so much about PHP. Today we will learn how to solve the PHP singleton mode analysis and practical combat in one step. I wonder if you have fully mastered it. If not, then follow this article Let’s continue learning with this article
1. What is the singleton pattern?
1. Meaning
## As an object creation mode, the singleton mode ensures that there is only one instance of a certain class, and it instantiates itself and provides this instance globally to the entire system. It does not create a copy of the instance, but returns a reference to the instance stored inside the singleton class.
2. Three key points of the singleton pattern:
(1). A static member variable is required to save the only instance of the class:
private static $_instance;
(2). The constructor and clone function must Declare it as private to prevent external programs from new classes and lose the meaning of the singleton mode:
private function __construct() { $this->_db = pg_connect('xxxx'); } private function __clone() { }//覆盖__clone()方法,禁止克隆
(3). A public static method to access this instance must be provided ( Usually getInstance method), thus returning a reference to the only instance
public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; }
2. Why use the singleton mode?
1. PHP Disadvantages:
PHP language is an interpreted scripting language. This operating mechanism allows all related resources to be recycled after each PHP page is interpreted and executed. In other words, PHP has no way to make an object resident in memory at the language level. This is different from compiled types such as asp.net and Java. For example, in Java, a singleton will always exist throughout the life cycle of the application. Variables are cross-page level and can truly make this instance unique in the application life cycle. However, in PHP, all variables, whether they are global variables or static members of the class, are page-level. Every time the page is executed, a new object will be re-established and will be cleared after the page is executed. It seems that PHP The singleton mode is meaningless, so I think the PHP singleton mode is very meaningful only when multiple application scenarios occur in a single page-level request and need to share the same object resource.
2. Application occasions of singleton mode in PHP:
(1), application and database interaction
## An application will There are a large number of database operations, such as connecting to the database through a database handle. Using the singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.
(2), control configuration information 如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现. 三、如何实现单例模式? 1、普通的数据库访问例子: 2、应用单例模式对数据库进行操作: 3、深入理解 推荐学习:《PHP视频教程》<?php
......
//初始化一个数据库句柄
$db = new DB(...);
//添加用户信息
$db->addUserInfo(...);
......
//在函数中访问数据库,查找用户信息
function getUserInfo()
{
$db = new DB(...);//再次new 数据库类,和数据库建立连接
$db = query(....);//根据查询语句访问数据库
}
?>
<?php
class DB
{
private $_db;
private static $_instance;
private function __construct(...)
{
$this->_db = pg_connect(...);//postgrsql
}
private function __clone() {}; //覆盖__clone()方法,禁止克隆
public static function getInstance()
{
if(! (self::$_instance instanceof self) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function addUserInfo(...)
{
}
public function getUserInfo(...)
{
}
}
//test
$db = DB::getInstance();
$db->addUserInfo(...);
$db->getUserInfo(...);
?>
<?php
class db {
public $conn;
public static $sql;
public static $instance=null;
private function __construct(){
require_once('db.config.php');
$this->conn = mysql_connect($db['host'],$db['user'],$db['password']);
if(!mysql_select_db($db['database'],$this->conn)){
echo "失败";
};
mysql_query('set names utf8',$this->conn);
}
public static function getInstance(){
if(is_null(self::$instance)){
self::$instance = new db;
}
return self::$instance;
}
/**
* 查询数据库
*/
public function select($table,$condition=array(),$field = array()){
$where='';
if(!empty($condition)){
foreach($condition as $k=>$v){
$where.=$k."='".$v."' and ";
}
$where='where '.$where .'1=1';
}
$fieldstr = '';
if(!empty($field)){
foreach($field as $k=>$v){
$fieldstr.= $v.',';
}
$fieldstr = rtrim($fieldstr,',');
}else{
$fieldstr = '*';
}
self::$sql = "select {$fieldstr} from {$table} {$where}";
$result=mysql_query(self::$sql,$this->conn);
$resuleRow = array();
$i = 0;
while($row=mysql_fetch_assoc($result)){
foreach($row as $k=>$v){
$resuleRow[$i][$k] = $v;
}
$i++;
}
return $resuleRow;
}
/**
* 添加一条记录
*/
public function insert($table,$data){
$values = '';
$datas = '';
foreach($data as $k=>$v){
$values.=$k.',';
$datas.="'$v'".',';
}
$values = rtrim($values,',');
$datas = rtrim($datas,',');
self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})";
if(mysql_query(self::$sql)){
return mysql_insert_id();
}else{
return false;
};
}
/**
* 修改一条记录
*/
public function update($table,$data,$condition=array()){
$where='';
if(!empty($condition)){
foreach($condition as $k=>$v){
$where.=$k."='".$v."' and ";
}
$where='where '.$where .'1=1';
}
$updatastr = '';
if(!empty($data)){
foreach($data as $k=>$v){
$updatastr.= $k."='".$v."',";
}
$updatastr = 'set '.rtrim($updatastr,',');
}
self::$sql = "update {$table} {$updatastr} {$where}";
return mysql_query(self::$sql);
}
/**
* 删除记录
*/
public function delete($table,$condition){
$where='';
if(!empty($condition)){
foreach($condition as $k=>$v){
$where.=$k."='".$v."' and ";
}
$where='where '.$where .'1=1';
}
self::$sql = "delete from {$table} {$where}";
return mysql_query(self::$sql);
}
public static function getLastSql(){
echo self::$sql;
}
}
$db = db::getInstance();
//$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password'));
//echo $db->insert('demo',array('name'=>'最近你啦','password'=>'123'));
//echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1));
echo $db->delete('demo',array('id'=>'2'));
db::getLastSql();
echo "<pre class="brush:php;toolbar:false">";
?>
The above is the detailed content of One trick to solve PHP singleton pattern analysis and practical combat. For more information, please follow other related articles on the PHP Chinese website!