Examples of PHP single example patterns sharing

Source: Internet
Author: User
Tags instance method

This article mainly shares an example of a PHP single example pattern, design patterns These flower point of mind Basic is able to understand, of course, want to very good application to the project is also need a certain practice, can not just know, or say is very strong understand, one to the actual operation is not, nonsense will not say more

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

The main points are three: 1. Must have only one instance. 2. This instance must be created automatically. 3. This example must be provided to the system as a whole.

The code is as follows:
?
Class mysql{
Privete static $instance;//Save Instance
Constructors are declared private to prevent the creation of objects directly
Privete function __construct () {
Instantiation of
}
Single-instance method to determine if it has been instantiated, only once
public static function getinstance () {
if (!isset (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
Prevent cloning of objects
Private Function __clone () {
Trigger_error ("not allow to clone.");
}
function Test () {
echo "Test";
}
}
$conn = Mysql::getinstance ();
$conn->test ();
?>

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.