search
HomeBackend DevelopmentPHP TutorialOne 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、普通的数据库访问例子:

<?php
......
//初始化一个数据库句柄
$db = new DB(...);

//添加用户信息
$db->addUserInfo(...);

......

//在函数中访问数据库,查找用户信息
function getUserInfo()
{
    $db = new DB(...);//再次new 数据库类,和数据库建立连接
    $db = query(....);//根据查询语句访问数据库
}

?>

2、应用单例模式对数据库进行操作:

<?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(...);


?>

3、深入理解

<?php
class db {
	public $conn;
	public static $sql;
	public static $instance=null;
	private function __construct(){
		require_once(&#39;db.config.php&#39;);
		$this->conn = mysql_connect($db[&#39;host&#39;],$db[&#39;user&#39;],$db[&#39;password&#39;]);
		if(!mysql_select_db($db[&#39;database&#39;],$this->conn)){
			echo "失败";
		};
		mysql_query(&#39;set names utf8&#39;,$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=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		$fieldstr = &#39;&#39;;
		if(!empty($field)){
			
			foreach($field as $k=>$v){
				$fieldstr.= $v.&#39;,&#39;;
			}
			 $fieldstr = rtrim($fieldstr,&#39;,&#39;);
		}else{
			$fieldstr = &#39;*&#39;;
		}
		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 = &#39;&#39;;
	 	$datas = &#39;&#39;;
	 	foreach($data as $k=>$v){
	 		$values.=$k.&#39;,&#39;;
	 		$datas.="&#39;$v&#39;".&#39;,&#39;;
	 	}
	 	$values = rtrim($values,&#39;,&#39;);
	 	$datas   = rtrim($datas,&#39;,&#39;);
	 	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=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		$updatastr = &#39;&#39;;
		if(!empty($data)){
			foreach($data as $k=>$v){
				$updatastr.= $k."=&#39;".$v."&#39;,";
			}
			$updatastr = &#39;set &#39;.rtrim($updatastr,&#39;,&#39;);
		}
		self::$sql = "update {$table} {$updatastr} {$where}";
		return mysql_query(self::$sql);
	}
	/**
	 * 删除记录
	 */
	 public function delete($table,$condition){
	 	$where=&#39;&#39;;
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."=&#39;".$v."&#39; and ";
			}
			$where=&#39;where &#39;.$where .&#39;1=1&#39;;
		}
		self::$sql = "delete from {$table} {$where}";
		return mysql_query(self::$sql);
		
	 }
	
	public static function getLastSql(){
		echo self::$sql;
	}
	
	
	
}

$db = db::getInstance();
//$list = $db->select(&#39;demo&#39;,array(&#39;name&#39;=>&#39;tom&#39;,&#39;password&#39;=>&#39;ds&#39;),array(&#39;name&#39;,&#39;password&#39;));
//echo $db->insert(&#39;demo&#39;,array(&#39;name&#39;=>&#39;最近你啦&#39;,&#39;password&#39;=>&#39;123&#39;));
//echo $db->update(&#39;demo&#39;,array("name"=>&#39;xxx&#39;,"password"=>&#39;123&#39;),array(&#39;id&#39;=>1));
echo $db->delete(&#39;demo&#39;,array(&#39;id&#39;=>&#39;2&#39;));
db::getLastSql();
echo "<pre class="brush:php;toolbar:false">";
?>

推荐学习:《PHP视频教程

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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools