Php Singleton mode example sharing _ PHP Tutorial

Source: Internet
Author: User
Example of php Singleton mode. Php Singleton mode example: This article mainly shares an example of the php Singleton mode. the design pattern is easy to understand, of course, it is necessary to use the example of the php Singleton mode for sharing.

This article mainly shares an example of the php Singleton mode. the design mode is easy to understand, of course, it also requires some practice to make good use of the project. you can't just understand it, or you can understand it very well. once it comes to practice, you won't be able to do it.

The Singleton mode is mainly used for database connection. it ensures that a database class has only one instance and provides this instance to the entire system. This prevents the new operation from consuming resources and the too transaction connection information in the database.

There are three key points: 1. there must be only one instance. 2. the instance must be created automatically. 3. you must provide this instance to the entire system.

The code is as follows:


Class mysql {
Privete static $ instance; // Save the instance
// The constructor declares private to prevent direct object creation.
Privete function _ construct (){
// Instantiate
}
// Singleton method, which determines whether the instance has been instantiated and is only instantiated once
Public static function getInstance (){
If (! Isset (self: $ instance )){
Self: $ instance = new self ();
}
Return self: $ instance;
}
// Prevent cloned objects
Private function _ clone (){
Trigger_error ("not allow to clone .");
}
Function test (){
Echo "test ";
}
}
$ Conn = mysql: getInstance ();
$ Conn-> test ();
?>

Ghost This article mainly shares an example of the php Singleton mode. the design mode is easy to understand. of course, if you want to use it well...

Related Article

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.