First of all, we need to clarify the concept of singleton mode, so what is a singleton model?
The singleton pattern, as its name implies, is only one instance.
As the creation mode of an object, the singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.
This class is what we call a singleton class.
The main points of the singleton pattern are three:
They must have a constructor and must be marked as private
They have a static member variable that holds an instance of the class
They have a public static method that accesses this instance
Unlike a normal class, a singleton class cannot be instantiated directly in another class. A singleton class can only be instantiated by itself. To obtain such a result, the __construct () method must be marked private. If you attempt to construct a class with the private constructor, you will get an accessibility level error.
For a singleton class to work, you must make it available to other classes with an instance that invokes various methods. The Singleton class does not create a copy of the instance, but instead returns a reference to the instance stored inside the singleton class. The result is that the Singleton class does not repeatedly consume memory and system resources, allowing other parts of the application to make better use of those resources. As part of this pattern, you must create an empty private __clone () method to prevent the object from being copied or cloned.
This method of returning an instance reference is usually named getinstance (). This method must be static, and if it has not yet been instantiated, it must be instantiated. The getinstance () method can detect whether a class has been instantiated by using the instanceof operator and the self keyword.
Header ("Content-type:text/html;charset=utf-8");
Single-Case test class
Class Test {
Private $unique;
static private $instance;//Property Save the class instance
Private Function __construct () {//Construction method proprietary (prevents external calls)
$this->unique=rand (0,20000);
}
static public Function getinstance () {///static method provides external interface (get instance)
if (!self:: $instance instanceof Self) {
Self:: $instance =new self ();
}
Return self:: $instance;
}
Private Function __clone () {}//proprietary cloning method to prevent the outside world from cloning the instance directly
}
$test =test::getinstance ();
$test 2=test::getinstance ();
Print_r ($test);
Print_r ($test 2);
if ($test = = = $test 2) {
echo ' Equal! ';
}else{
echo ' Not equal! ';
}
Results:
An analysis of PHP singleton model