Home > Backend Development > PHP Tutorial > PHP design pattern singleton pattern

PHP design pattern singleton pattern

不言
Release: 2023-03-24 09:54:02
Original
1600 people have browsed it

The content of this article is about the singleton mode of PHP design pattern, which has certain reference value. Now I share it with you. Friends in need can refer to it

Single case mode ( Singleton) is also one of the creative modes, and it is not difficult to understand.
After reading some information, the most basic application is the task manager.
In fact, my personal understanding is that cannot create a second identical object.

The program will internally determine whether the object has been created. If not, create it. If it already exists, use it directly.

Made some simple records, as follows:

<?php  
     
    
/** Singleton  
 *  单例模式类 
 *  @static $obj 
 *  @var $hero 
 */   
class Singleton    
{    
    // 创建静态对象变量    
    private static $obj = null;    
    
    // 当前对象里面的人物  
    public $hero;    
  
    //实例化对象变量方法,供外部调用    
    public static function getInstance()    
    {    
        // 判断对象是否创建  
        if(empty(self::$obj))    
        {    
            // 如果没有创建对象 创建并保存   
            self::$obj = new Singleton();   
        }    
  
        // 如果创建了直接返回   
        return self::$obj;    
    }    
}
Copy after login
<?php  
// 单例模式 index.php  
header("Content-Type:text/html;charset=utf-8");  
require_once "Singleton.php";  
  
// 第一次调用实例化对象变量方法  
$single1 = Singleton::getInstance();    
// 给 hero赋值为 诸葛亮   
$single1->hero = "诸葛亮";  
echo "single1创建的英雄为:{$single1->hero}<br/>";    
  
// 第二次调用实例化对象变量方法 程序会判断出对象已经创建过,直接使用。  
$single2 = Singleton::getInstance();    
// 给hero赋值为 周瑜,会直接覆盖第一次的诸葛亮  
$single2->hero = "周瑜";    
  
echo "single1创建的英雄为:{$single1->hero}<br/>";    
  
echo "single2创建的英雄为:{$single2->hero}<br/>";
Copy after login


##The output result is:

The hero created by single1 is: Zhuge Liang
The hero created by single1 is: Zhou Yu
The hero created by single2 is: Zhou Yu

Related recommendations :

Abstract Factory of PHP Design Pattern

Factory Method of PHP Design Pattern

PHP Design Pattern Simple Factory

The above is the detailed content of PHP design pattern singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template