This article is not necessarily perfect for the explanation of the PHP single example mode! Just give an example, the purpose is to let myself through an example can deepen the understanding of the single case mode! Here, for reference only!
Single example: It is simple to understand that a class can only instantiate a single object and cannot instantiate multiple objects!
Class E {
Public $uname;
static $obj = NULL; Define a static property
Private Function __construct () { ///The private property is used before the method is constructed in order to not instantiate the object outside of the class.
That cannot $a=new e ();
//If you want to instantiate an object using the New keyword, the constructor is called.
This function has been decorated as private, and an error is made when instantiating the object with the New keyword.
static function Getobj () {
if (Is_null (self:: $obj)) {
Self:: $obj = new E (); The internal instantiation object of the class is assigned to the static property, and the first time the object is instantiated,
The//$obj will be assigned, and when the object is instantiated later,
Return self:: $obj; Because there's a judgment here. The instance object will only instantiate the object once;
///Multiple objects are instantiated, only the object's reference is assigned to the variable, the object is not instantiated again
}
$d = E::getobj ();
$d->uname = 100;
Echo $d->uname; 100
$e = E::getobj ();
$e->uname = 200;
Echo $d->uname; Output, the uname value of the $d object is also in the table because $e and $d point to the same object
Echo $e->uname; Will output 200