Home Backend Development PHP Tutorial API Development Part 3: PHP Design Pattern: The Perfect Singleton Pattern

API Development Part 3: PHP Design Pattern: The Perfect Singleton Pattern

Aug 08, 2016 am 09:30 AM
function self static

Today let’s talk about the singleton pattern.

Because I used to do java development, when using the singleton mode, I first thought of using the hungry Chinese style, and then I found that in PHP, there is such a feature: because PHP does not support giving in the class definition Member variables of a class are assigned values ​​of non-basic types. Such as expressions, new operations, etc. So the Hungry Chinese style will not work. Instead, I wanted to ensure the atomicity of this singleton mode, and found that there are no thread safety issues in PHP like in JAVA. Hey, do you think PHP is good? OK, then let’s try PHP’s lazy singleton mode.

Let’s not talk about it for now, let me start with my first version of the singleton mode code:

    // 定义私有静态变量.此种方式为:懒汉式单例(PHP中只有这种方式)
    private static $instance = null;
    // 私有化构成方法
    private function __construct(){
    }
    // 提供获取实例的公共方法
    public static function getInstance(){
        if(!(self::$instance instanceof self)){
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    // 私有__clone方法,禁止复制对象
    private function __clone(){

    }
Copy after login
OK, this code looks perfect, with comments and formatting, there is no problem. But when I was using it, I discovered a problem

My class A is in singleton mode, and then my class B inherits from class A, and then I call the following method:

$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);
Copy after login
The output result It is: bool(true)
What does this output mean? That is to say: after B inherits from A, my original intention is that B also becomes a singleton mode. Then A and B only inherit and manage, and their objects should not be equal. But now the two objects are exactly the same, which can only mean: The object obtained through
$b = B::getInstance();
Copy after login
is still an object of class A, so what's going on?

The problem lies with self. The reference of self is determined when the class is defined. That is to say, if A inherits B, its self reference still points to A. To solve this problem, the late static binding feature was introduced in PHP 5.3. Simply put, static methods or variables are accessed through the static keyword. Unlike self, static references are determined at runtime. So we simply rewrite our code so that the singleton mode can be reused.

class C
{
    protected static $_instance = null;
    protected function __construct(){
    }
    protected function __clone(){
    }
    public function getInstance(){
        if (static::$_instance === null) {
            static::$_instance = new static;
        }
        return static::$_instance;
    } 
}
class D extends C{
    protected static $_instance = null;
}
$c = C::getInstance();
$d = D::getInstance();
var_dump($c === $d);
Copy after login
The output at this time will become: bool(false)

Then it can be achieved. As long as you inherit this singleton mode, then its subclasses will also be singleton mode. This can achieve perfect reuse without having to write so much repeated code every time you need the singleton mode. Note that the above method can only be used in PHP 5.3. For previous versions of PHP, it is better to write a getInstance() method for each singleton class.

The above has introduced the third part of API development: PHP's design pattern - the perfect singleton pattern, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

How to use self in Python How to use self in Python May 17, 2023 pm 10:40 PM

Before introducing the usage of self in Python, let’s first introduce the classes and instances in Python. We know that the most important concepts of object-oriented are classes and instances. Classes are abstract templates, such as abstract things like students. , can be represented by a Student class. Instances are specific "objects" created based on classes. Each object inherits the same methods from the class, but its data may be different. 1. Take the Student class as an example. In Python, the class is defined as follows: classStudent(object):pass(Object) indicates which class the class inherits from. The Object class is all

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

The usage and function of Vue.use function The usage and function of Vue.use function Jul 24, 2023 pm 06:09 PM

Usage and Function of Vue.use Function Vue is a popular front-end framework that provides many useful features and functions. One of them is the Vue.use function, which allows us to use plugins in Vue applications. This article will introduce the usage and function of the Vue.use function and provide some code examples. The basic usage of the Vue.use function is very simple, just call it before Vue is instantiated, passing in the plugin you want to use as a parameter. Here is a simple example: //Introduce and use the plug-in

clearstatcache() function in PHP clearstatcache() function in PHP Sep 07, 2023 am 09:33 AM

The clearstatcache() function is used to clear the file status cache. PHP caches the information returned by the following functions −stat()lstat()file_exists()is_writable()is_readable()is_executable()is_file()is_dir()filegroup()fileowner()filesize()filetype()fileperms() What to do To provide better performance. Syntax voidclearstatecache() Parameter NA Return value clearstatcache(

What is the function and usage of static in C language What is the function and usage of static in C language Jan 31, 2024 pm 01:59 PM

The role and usage of static in C language: 1. Variable scope; 2. Life cycle; 3. Internal function; 4. Modify global variables; 5. Modify function; 6. Other uses; Detailed introduction: 1. Variable scope, when If there is the static keyword before a variable, then the scope of the variable is limited to the file in which it is declared. In other words, the variable is a "file-level scope", which is very useful for preventing the "duplicate definition" problem of variables; 2. Life cycle, static variables are initialized once when the program starts executing, and destroyed when the program ends, etc.

See all articles