PHP singleton mode sample sharing, PHP mode sample sharing _php Tutorial

Source: Internet
Author: User

PHP singleton mode sample sharing, PHP pattern sample sharing


The singleton mode is primarily used for database connections, ensuring that the database has only one instance of a class and provides this instance to the entire system. This prevents new operations from consuming resources while avoiding too many connection information in the database.

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

Copy the Code code as follows:
<?
Class mysql{
Privete static $instance;//Save Instance
The constructor is declared private, preventing the object from being created directly
Privete function __construct () {
Instantiation of
}
A singleton method that determines if it has been instantiated and instantiates only 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.html www.bkjia.com true http://www.bkjia.com/PHPjc/957122.html techarticle PHP Singleton mode sample sharing, PHP mode sample sharing singleton mode is mainly used in the database connection, to ensure that the database has only one instance of a class, and to provide this reality to the entire system ...

  • 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.