Home>Article>Backend Development> Singleton pattern in php

Singleton pattern in php

autoload
autoload Original
2021-03-02 17:17:58 6088browse

1. The origin of the singleton pattern

Classis an abstraction of a class of things with common characteristics in real life. Through the instantiation of a class, many objects are generated, but at the same time it also consumes a lot of resources (such as the limit on the number of connections when connecting to thedatabase, and for example, opening theresource manager on the computerhas uniqueness), which also resulted in the need to limit the instantiation of the class. In order to protect the uniqueness of resources,single case modewas born.

2. Definition of singleton pattern

Definition: Singleton pattern is a design idea that a class design will only produce at most one object.

3. Instance of singleton mode

a. Create an empty class.

b. Being able to instantiate a class multiple times is the reason why multiple objects are generated, so you can privatize the

constructor method.

c. Privatization

Constructor methodmakes the number of instantiated objects generated to 0, so that the constructor method can be called throughstatic methodinside the class , and then return the constructor to the outside.

"; } } ?>

d. Although the object can be instantiated through the above method, it also releases the use rights of the constructor method. If you want this method to return only one object, you must ensure that there is a way to store a generated object inside the class. A new one is generated for the first time, and the old one is returned later. In this case, you need to use static properties.

"; } public static function getInstance() { return new self(); } } $s1=Use::getSingleton(); ?>

e. At this time, it can be guaranteed that only one

objectwill be obtained by calling thestatic method. However, you can still instantiate new objects throughclone, so you can privatizeclone.

"; } public static function getInstance() { //判断类内部的静态属性是否存在对象 if(!(self::$object instanceof self)){ //当前保存的内容不是当前类的对象 self::$object = new self(); } //返回对象给外部 return self::$object; } } $s1=Use::getSingleton(); ?>

Recommended:php tutorial

The above is the detailed content of Singleton pattern in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn