search
HomeBackend DevelopmentPHP TutorialIntroduction and examples of PHP singleton pattern

  1. private static $_instance;
Copy code

2), constructors and clone functions must be declared private to prevent external programs from new classes and lose the meaning of the singleton mode:

  1. private function __construct()
  2. {
  3. $this->_db = pg_connect('xxxx');
  4. }
  5. private function __clone()
  6. {
  7. }//Override __clone() method, prohibited Clone
Copy code

(3). You must provide a public static method to access this instance (usually the getInstance method), thereby returning a reference to the unique instance

  1. public static function getInstance()
  2. {
  3. if(! (self::$_instance instanceof self) )
  4. {
  5. self::$_instance = new self();
  6. }
  7. return self::$ _instance;
  8. }
Copy code

2. Why should we use the singleton mode of PHP design pattern? 1. PHP Disadvantages: The PHP language is an interpreted scripting language. This operating mechanism ensures that after each PHP page is interpreted and executed, all related resources will be recycled. 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) Interaction between application and database There will be a large number of database operations in an application, such as the act of 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 If a class is needed in the system to globally control certain configuration information, then it can be easily implemented using the singleton pattern.

3. How to implement singleton mode? 1. Common database access examples:

  1. ......
  2. //Initialize a database handle
  3. $db = new DB(...);
  4. //Add user information
  5. $db->addUserInfo (...);
  6. ......
  7. //Access the database in the function to find user information
  8. function getUserInfo()
  9. {
  10. $db = new DB(...);//new again Database class, establish a connection with the database
  11. $db = query(....);//Access the database according to the query statement
  12. }
  13. ?>
Copy the code

2. Apply singleton mode to operate the database :

  1. class DB
  2. {
  3. private $_db;
  4. private static $_instance;
  5. private function __construct(...)
  6. {
  7. $this->_db = pg_connect(.. .);//postgrsql
  8. }
  9. private function __clone() {}; //Override the __clone() method and prohibit cloning
  10. public static function getInstance()
  11. {
  12. if(! (self::$_instance instanceof self) ) {
  13. self::$_instance = new self();
  14. }
  15. return self::$_instance;
  16. }
  17. public function addUserInfo(...)
  18. {
  19. }
  20. public function getUserInfo(... )
  21. {
  22. }
  23. }
  24. //test
  25. $db = DB::getInstance();
  26. $db->addUserInfo(...);
  27. $db->getUserInfo(...);
  28. ?>
Copy code

3. In-depth understanding

  1. /**
  2. Database operation class
  3. @link http://bbs.it-home.org
  4. */
  5. class db {
  6. public $conn;
  7. public static $sql;
  8. public static $instance=null;
  9. private function __construct(){
  10. require_once('db.config.php');
  11. $this->conn = mysql_connect($db['host'],$db['user'],$db['password']);
  12. if(!mysql_select_db($db['database'],$this->conn)){
  13. echo "失败";
  14. };
  15. mysql_query('set names utf8',$this->conn);
  16. }
  17. public static function getInstance(){
  18. if(is_null(self::$instance)){
  19. self::$instance = new db;
  20. }
  21. return self::$instance;
  22. }
  23. /**
  24. * Query database
  25. */
  26. public function select($table,$condition=array(),$field = array()){
  27. $where='';
  28. if(!emptyempty($condition)){
  29. foreach($condition as $k=>$v){
  30. $where.=$k."='".$v."' and ";
  31. }
  32. $where='where '.$where .'1=1';
  33. }
  34. $fieldstr = '';
  35. if(!emptyempty($field)){
  36. foreach($field as $k=>$v){
  37. $fieldstr.= $v.',';
  38. }
  39. $fieldstr = rtrim($fieldstr,',');
  40. }else{
  41. $fieldstr = '*';
  42. }
  43. self::$sql = "select {$fieldstr} from {$table} {$where}";
  44. $result=mysql_query(self::$sql,$this->conn);
  45. $resuleRow = array();
  46. $i = 0;
  47. while($row=mysql_fetch_assoc($result)){
  48. foreach($row as $k=>$v){
  49. $resuleRow[$i][$k] = $v;
  50. }
  51. $i++;
  52. }
  53. return $resuleRow;
  54. }
  55. /**
  56. * Add a record
  57. */
  58. public function insert($table,$data){
  59. $values = '';
  60. $datas = '';
  61. foreach($data as $k=>$v){
  62. $values.=$k.',';
  63. $datas.="'$v'".',';
  64. }
  65. $values = rtrim($values,',');
  66. $datas = rtrim($datas,',');
  67. self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})";
  68. if(mysql_query(self::$sql)){
  69. return mysql_insert_id();
  70. }else{
  71. return false;
  72. };
  73. }
  74. /**
  75. * Modify a record
  76. */
  77. public function update($table,$data,$condition=array()){
  78. $where='';
  79. if(!emptyempty($condition)){
  80. foreach($condition as $k=>$v){
  81. $where.=$k."='".$v."' and ";
  82. }
  83. $where='where '.$where .'1=1';
  84. }
  85. $updatastr = '';
  86. if(!emptyempty($data)){
  87. foreach($data as $k=>$v){
  88. $updatastr.= $k."='".$v."',";
  89. }
  90. $updatastr = 'set '.rtrim($updatastr,',');
  91. }
  92. self::$sql = "update {$table} {$updatastr} {$where}";
  93. return mysql_query(self::$sql);
  94. }
  95. /**
  96. * Delete record
  97. */
  98. public function delete($table,$condition){
  99. $where='';
  100. if(!emptyempty($condition)){
  101. foreach($condition as $k=>$v){
  102. $where.=$k."='".$v."' and ";
  103. }
  104. $where='where '.$where .'1=1';
  105. }
  106. self::$sql = "delete from {$table} {$where}";
  107. return mysql_query(self::$sql);
  108. }
  109. public static function getLastSql(){
  110. echo self::$sql;
  111. }
  112. }
  113. $db = db::getInstance();
  114. //$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password'));
  115. //echo $db->insert('demo',array('name'=>'最近你啦','password'=>'123'));
  116. //echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1));
  117. echo $db->delete('demo',array('id'=>'2'));
  118. db::getLastSql();
  119. echo "
    ";  
  120. ?>
复制代码



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment