PHP singleton mode sample sharing _php Tutorial

Source: Internet
Author: User

PHP Singleton mode sample sharing


This article mainly shared a PHP singleton model of the example, design patterns of these flowers point of view of the basic is able to understand, of course, it is necessary to apply to the project is a certain practice, can not just know, or is very strong understand, one to the actual operation will not, nonsense will not say more

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.

The code is 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/957533.html www.bkjia.com true http://www.bkjia.com/PHPjc/957533.html techarticle PHP Singleton mode sample sharing this article mainly shared a PHP singleton pattern of examples, design patterns These flowers point of view of the basic is understandable, of course, to be very good use of the item ...

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