This article does not necessarily improve the interpretation of PHP singleton mode! Just to give an example, the purpose is to let me through an instance can deepen the understanding of the singleton mode! Here, for reference only!
Singleton: It is simple to understand that a single object can only be instantiated through a class, and multiple objects cannot be instantiated!
Class E {
Public $uname;
static $obj = NULL; //Define a static property
Private Function __construct () { //Use the private property before constructing the method, in order to not instantiate the object outside the class.
That cannot $a=new e ();
} //If you want to instantiate an object using the New keyword, the constructor is called.
The function has been decorated as private, and an error occurs when instantiating an object using the New keyword.
static function Getobj () {
if (Is_null (self:: $obj)) {
Self:: $obj = new E (); //The object is assigned to a static property in the inner instantiation of the class, and the first time the object is instantiated,
} //$obj will be assigned, and when the object is instantiated later,
Return self:: $obj; // the instance object is not repeated because there is a judgment here The object is instantiated only once;
} // instantiating an object more than once, simply assigning the object's reference to the variable and not instantiating the object again
}
$d = E::getobj ();
$d->uname = 100;
Echo $d->uname; 100
$e = E::getobj ();
$e->uname = 200;
Echo $d->uname; //Outputs a maximum of $d the uname value of the object is also the table because $e and $d point to the same object
Echo $e->uname; //Will output
An example of PHP's singleton pattern