PHP singleton mode example sharing, PHP mode example sharing_PHP tutorial

WBOY
Release: 2016-07-13 10:07:01
Original
819 people have browsed it

Sharing of php singleton mode examples, sharing of php mode examples

The singleton mode is mainly used for database connections, ensuring that there is only one instance of a class in the database, and providing this instance to the entire system. This prevents the new operation from consuming resources and avoids too many connection information appearing in the database.

There are three main points: 1. There must be only one instance. 2. This instance must be created automatically. 3. This instance must be provided to the entire system.

Copy code The code is as follows:

class mysql{
          private static $instance ;//Save instance
//The constructor is declared as private to prevent direct creation of objects
         private function __construct(){
// instance <化>          }
//Single case method, determine whether it has been instantiated, and only instantiate it once
           public static function getInstance (){
If(!isset( self::$instance )){
                      self ::$instance = new self();
            }
               return self:: $instance;
         }
//Prevent cloning objects
           private function __clone (){
              trigger_error ("not allow to clone.");
         }
          function test(){
                  echo "test" ;
         }
}
$conn = mysql::getInstance ();
$conn->test ();
?>

http://www.bkjia.com/PHPjc/957122.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/957122.htmlTechArticlephp singleton mode example sharing, php mode example sharing singleton mode is mainly used for database connections, ensuring a database A class has only one instance, and provides this implementation to the entire system...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template