PHP Single example mode detailed introduction and realization Source _php example

Source: Internet
Author: User
Tags mysql connect php database

This article mainly introduced the PHP database single example pattern realization code sharing, this article first explained the single case pattern some knowledge, then gave the database single example pattern realization code.

What is a single case pattern

Singleton mode, as the name suggests, is only one instance.

As an object's creation pattern, the singleton pattern ensures that a class has only one instance, and instantiates it and provides the entire system with this instance, which we call a singleton class.

The main points of a single case pattern are three:

One is that a class can have only one instance;
The second is that it must create this instance by itself;
Third, it must provide this example to the whole system.

Why use PHP as a single case mode?

1, the application of PHP is mainly in the database application, so an application will have a large number of database operations, the use of single case mode, you can avoid a large number of new operations to consume resources

2, if the system needs to have a class to global control of some configuration information, then use a single example mode can be very convenient to implement. This can be frontcontroller part of ZF.

3, in a page request, easy to debug, because all the code (such as database Operation class DB) are concentrated in a class, we can set hooks in the class, output log, so as to avoid everywhere var_dump, Echo

Single Case class

1. Constructors need to be marked private (access control: Prevents external code from using the new operator to create an object), a singleton class cannot be instantiated in another class, and can only be instantiated by itself

2. Have a static member variable that holds an instance of the class

3. Have a public static method to access this instance (commonly used getinstance () method to instantiate a singleton class, through the instanceof operator can detect whether the class has been instantiated)

4. In addition, you need to create a __clone () method to prevent objects from being replicated (clones)

The implementation method of PHP single example mode

A single case pattern can save resources in a particular situation, such as multiple operations on the same page facing a database, and no need to go to New times to save resources.

The key to a singleton pattern is the "instanceof" in PHP, which detects whether a variable is an instance of a class.

Also, to prevent users from going to the new instance, you need to set the "__construct" function permission to private.

To prevent the user from cloning, rewrite the "__clone" method.

<?php * * Single Case database connection/class Db {private static $_instance;//static can save value without losing private static $_dbconnect;  Private $_dbconfig = Array (' Host ' => ' 127.0.0.1 ', ' user ' => ' root ', ' password ' => ', ' database '
  => ' Yii2basic ',)//Save configuration information for database//use private to prevent user new Private function __construct () {}//rewrite clone to prevent user from cloning
  The Public Function __clone () {//generates an error message when user clone operation Trigger_error ("Can ' t clone object", E_user_error); //instantiated by the class itself (Author: code Agriculture tutorial http://www.manongjc.com) public static function getinstance () {if (!
    Self::$_instance instanceof Self)) {self::$_instance = new self ();
  return self::$_instance; The Public Function connect () {Self::$_dbconnect = @mysql_connect ($this->_dbconfig[' host '), $this->_dbcon

    fig[' user '], $this->_dbconfig[' password ']);
      if (!self::$_dbconnect) {throw new Exception ("MySQL connect error". Mysql_error ());
  Die ("MySQL connect error". Mysql_error ());  } mysql_query ("SET NAMES UTF8");
    mysql_select_db ($this->_dbconfig[' database '],self::$_dbconnect);
  return self::$_dbconnect;
}} $a = Db::getinstance (); try{$a->connect ();} catch (Exception $e) {echo "Sorry,error was happend.".
$e->getmessage (); }

Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.