First, what is a singleton mode?
A class can have an instance object that, when instantiated automatically, provides this instance object to the entire system
Second, what is the role?
Use the same instance object, not new, to reduce system resource waste
Three, what is the characteristic?
Class "Disallow inheritance" for final identity
Private constructor "prevent out-of-class instantiation"
Private cloning method "forbidden to be cloned"
Private static Property "Save instance object of Class"
public static function "calling interface of Class"
Purpose of the above behavior: to prevent the program from re-instantiating "consuming new resources"
Iv. Application Scenarios
Commonly used database operation class, every time using the database pants Operation class to new one object, for the system and memory resources waste is huge, and every new one to connect with the database, then the database connection number will run out quickly
V. Examples
<?PHPFinal classsingle{Private $rand= 0; //Storing instantiated objects Static Private $obj=NULL; //prevent out-of-class instantiation Private function__construct () {return $this-Rand=Mt_rand(1,99999); } //calling the interface of a class Static Public functionUSB () {if(!self::$obj) { self::$obj=NewSingle (); } returnSelf::$obj; } Public functionFFF () {Echo $this-Rand; } //prevent user cloning Private function__clone () {Echo' Forbid cloning! ‘; }}$single 1= Single::USB ();$single 2= Single::USB ();Print_r($single 1);Print_r($single 2);$single 2-FFF ();
PHP Single-instance mode