The singleton pattern literally means that there is only one instance of a class, so the benefits are very large, such as database connection, we only need to instantiate once, do not need to go to new each time, this greatly reduces the cost of resources.
The Singleton class has at least the following three common elements:
Must have a constructor and must be marked private.
has a static member variable that holds an instance of the class.
Have a public static method that accesses this instance
For specific use, I have commented clearly in the following PHP example:
<?PHP/** * by www.phpddt.com*/ class Mysql{ //This property is used to save the instance Private Static $conn; //The constructor is private, preventing the object from being created Private function__construct () {$this->conn =mysql_connect(' localhost ', ' root ', '); } //Create a method to instantiate an object Public Static functiongetinstance () {if(! (Self::$conninstanceof Self)) { Self::$conn=NewSelf ; } returnSelf::$conn; } //prevent objects from being copied Public function__clone () {Trigger_error(' Clone is not allowed! ')); } } //you can only get instances like this, not new and clone $mysql=Mysql::getinstance ();?>
PHP Single-instance class