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 (); An internal instantiation of an object in a class is assigned to a static property, and the first time the object is instantiated,
}//$obj will be assigned, and when the object is instantiated later,
Return self:: $obj; Because there are judgments here, the instance object will not be repeated 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; The uname value of the $d object is output to the table because $e and $d point to the same object
Echo $e->uname; Will output 200