Home  >  Article  >  Backend Development  >  Detailed explanation of useless PHP singleton mode application_PHP tutorial

Detailed explanation of useless PHP singleton mode application_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:09:23842browse

There are three main points of the singleton pattern:
First, a class can only have one instance;
Second, it must create this instance by itself;
Third, it must Provide this instance to the entire system yourself.

Copy code The code is as follows:

/* Example of singleton mode, which The key points are as follows:
*
* 1. $_instance must be declared as a static private variable
* 2. The constructor and clone function must be declared as private, this is to prevent external programs from new classes Thus losing the meaning of the singleton mode
* 3. The getInstance() method must be declared as public, and this method must be called to return a reference to the unique instance
* 4. The :: operator can only access static variables or Static function
* 5. PHP’s singleton mode is relatively speaking, because PHP’s interpretation and execution mechanism causes 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. In PHP, all variables are page-level. Whether they are global variables,
* or static members of the class, they will be cleared after the page is executed. As a result, new objects will be re-established, so that they are completely lost. Understand the meaning of Singleton.
* However, in actual applications, there may be multiple business logics in the same page. At this time, the singleton mode plays a very important role, effectively avoiding duplication of
* new objects (Note: new Objects will consume memory resources) such a behavior, so we say that PHP's singleton mode is relatively speaking
*
*/
class People
{
static private $_instance = NULL ;
public $height = '';
public $age = '';
private function __construct()
{
$this->height = '185';
$this->age = 25;
}
private function __clone()
{
//do something
}
static public function getInstance()
{
if(!self::$_instance instanceof self)
{
//echo 'lgh-big';
self::$_instance = new self;
}
else
{
//for testing only
//echo 'gdc-xiaoairener';
}
return self::$_instance;
}
public function getHeight()
{
echo $this->height;
}
public function getAge()
{
echo $this->age;
}
}
function testInstance()
{
People::getInstance()->getAge();
}
//begin to use the class
$lgh = People::getInstance ();
$lgh->getHeight();
echo '
';
testInstance();
?>

Advantages: The singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources
Disadvantages: 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. This way It seems that the PHP singleton mode has little meaning, so I think the PHP singleton mode is very meaningful only when multiple application scenarios occur during a single page-level request and need to share the same object resources.

Why – Why use PHP singleton pattern?
One of the main application scenarios of PHP is the application scenario where the application deals with the database, so there will be a large number of database operations in an application, such as the behavior of connecting to the database through the database handle, using a singleton The mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.
It is still a bit abstract and gives code snippets.
Use traditional coding
Copy the code The code is as follows:

......
//Initialize a database handle
$db = new DB(...);
//For example, there is The application scenario is to add a piece of user information:
$db->addUserInfo();
......
//However, we may need to find the user's information in another place. This scenario occurs In a function, when database handle resources are used, we may need to do this
...
function test(){
...
/ /At this time we have to re-initialize a database handle. Just imagine how terrible this code is in multiple application scenarios? !
$db = new DB(...);
$db->getUserInfo();
...
//Some friends may say, I don’t have to To do this, can't I just use the global keyword directly? Indeed, global can solve problems and also plays the role of singleton mode. However, in OOP, we refuse to write code like this because global has security risks. Please refer to relevant books. At the same time, singleton mode is exactly a kind of global variable. Improvement to avoid global variables that store unique instances from polluting the namespace
global $db; //In OOP, we do not advocate writing code like this
...
}

Coding using singleton pattern
Copy the code The code is as follows:

.. ....
//There is only one database handle resource for all application scenarios. Hey, the efficiency is very high.
//Resources are also greatly saved, and the code is concise and clear:)
DB::getInstance ()->addUserInfo();
DB::getInstance()->getUserInfo();
......

How – How to write PHP singleton pattern?
After understanding the application scenarios of the singleton mode, let’s master the core points of the PHP singleton mode by writing the specific implementation code of the singleton mode. The code is as follows:
Copy code The code is as follows:

/**
* PHP singleton mode demonstration example
* @author guohua.li
* @modify 2010-07-11
* @website http://blog.163.com/lgh_2002/
*/
class User{
/**
* Static finished variable saves global instance
* @access private
*/
static private $_instance = NULL;
/**
* Private constructor to prevent external objects from instantiating objects
*/
private function __construct() {}
/**
* Private clone function to prevent external objects from being cloned
*/
private function __clone(){}
/**
* Static method, singleton unified access entrance
* @return object Returns the only instance of the object
*/
static public function getInstance() {
if (is_null(self::$_instance) || !isset(self ::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Test method: Get user name
*/
public function getName() {
echo 'hello liguohua!';
}
}

From the above code, we summarize the following three core points for the implementation of PHP singleton mode:
1. A static member variable that holds the only instance of the class is required (usually $_instance Private variables)
2. Constructors and clone functions must be declared private. This is to prevent external programs from new classes and thus lose the meaning of the singleton mode
3. A public static method must be provided to access this instance. (usually the getInstance method), thus returning a reference to the unique instance
Disadvantages of the PHP singleton mode
As we all know, the PHP language is an interpreted scripting language , this operating mechanism causes 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327290.htmlTechArticleThere are three main points of the singleton pattern: First, a class can only have one instance; Second, it must be self-contained Create this instance; third, it must provide this instance to the entire system by itself. Copy code...
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