One instance of PHP Singleton mode
This article does not necessarily explain the PHP Singleton mode! I just want to give an instance, so that I can better understand the Singleton mode through an instance! This is for your reference only!
Singleton: it can be simply understood that a class can only instantiate a single object, but not multiple objects!
Class e {
Public $ uname;
Static $ obj = NULL; // defines a static property.
Private function _ construct (){ // Use the private attribute before the constructor. the object cannot be instantiated outside the class,
// It cannot be $ a = new e ();
} // If you want to use the new keyword to instantiate an object, the constructor will be called,
// This function has been modified to private. an error is returned when the new keyword is used to instantiate an object.
Static function getObj (){
If (is_null (self: $ obj )){
Self: $ obj = new e (); // The Static attribute is assigned to the instantiated object inside the class. when the object is instantiated for the first time,
} // $ Obj is assigned a value. When an object is instantiated later,
Return self: $ obj; // because of this judgment, the instance object will not be repeated and will only be instantiated once;
} // When an object is instantiated for multiple times, it only assigns the object reference value to the variable and does not instantiate the object again.
}
$ D = e: getObj ();
$ D-& gt; uname = 100;
Echo $ d-> uname; // 100
$ E = e: getObj ();
$ E-& gt; uname = 200;
Echo $ d-> uname; // The output value is 200. the uname value of the $ d object is also in this table, because $ e and $ d point to the same object.
Echo $ e-> uname; // output 200