Home>Article>Backend Development> A brief discussion on the understanding of PHP singleton mode and sample code

A brief discussion on the understanding of PHP singleton mode and sample code

little bottle
little bottle forward
2019-04-19 16:05:50 2266browse

This article is about understanding the PHP singleton mode. Friends who are interested should learn more!

Why use singleton mode?
I checked the information online and recorded it so that I can check it later.
Singleton mode, as the name suggests, has only one instance. It can save memory and resources, mainly because when PHP is dealing with the database, every new object will consume a certain amount of resources.

As we all know, the 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

, which 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 during a single page

level request and need to share the same object resource.

Without further ado, let’s start with the code



class User
{
/*
* 1、创建一个存放对象的私有化静态变量
* 2、私有化克隆方法
* 3、私有化构造方法
* 4、创建实例化对象的唯一入口
*
* **/
private static $_instance = '';
private function __clone(){}
private function __construct(){}
static public function getInstance()
{
if(is_null(self::$_instance) || isset(self::$_instance)){
self::$_instance = new User();
}
return self::$_instance;
}
public function getIp()
{
return $_SERVER['SERVER_ADDR'];
}
}
$op = User::getInstance();
echo $op->getIp();

Related tutorials:PHP video tutorial

The above is the detailed content of A brief discussion on the understanding of PHP singleton mode and sample code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete