SoFunction
Updated on 2025-04-07

Analysis of the method of simply implementing singleton design pattern in php

This article describes the method of simply implementing single-state design patterns in PHP. Share it for your reference, as follows:

A single-state design pattern usually contains the following three points:

· A private constructor; (make sure that the user cannot instantiate the object by creating it)
· A public static method; (responsible for instantiating itself)
· A private static property; (used to save only one instantiated object)

<?php
class singleTon{
    // Used to save only one instantiated object    private static $Instance=NULL;
    //Constructor method After using private encapsulation, you can only use new inside the class to create objects    private function __construct(){};
    //Only through this method can the object in this class be returned. This method is a static method called with the class name    public static getInstance(){
       if(self::$Instance instanceof self){ //If $Instance in this class is empty, it means that it has not been instantiated yet         self::$Instance=new singleTon(); //Instantiate this object       }
       return self::$Instance;
    }
}
$instance=singleTon::getInstance(); //Only use the static method getInstance() to get the object of the singleTon class?>

The so-called monomorphic design pattern is that a class can only generate/create a unique object.

To write a single-state design pattern, one must make a class only instantiate one object. If one wants a class only instantiate one object, one must first make one class not instantiate an object

For more information about PHP related content, please check out the topic of this site:PHP object-oriented programming tutorial》、《Introduction to PHP basic syntax》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.