Home Backend Development PHP Problem How to implement singleton mode in php

How to implement singleton mode in php

Aug 06, 2020 pm 02:07 PM
php Singleton pattern

php method to implement singleton mode: first create a static private variable to save the object of this class; then prevent the use of new to directly create the object; then prevent the use of clone to clone the object; finally determine whether [$instance] is a Singleton Object, if not, just create it.

How to implement singleton mode in php

php method to implement singleton mode:

Definition of singleton mode: ensure that a class has only one instance , and provide a global access point to it.

PHP implements singleton mode:

class Singleton
{
    //创建静态私有的变量保存该类对象
    static private $instance;
    //防止使用new直接创建对象
    private function __construct(){}
    //防止使用clone克隆对象
    private function __clone(){}
    static public function getInstance()
    {
        //判断$instance是否是Singleton的对象,不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function test()
    {
        echo "我是一个单例模式";
    }
}
$sing = Singleton::getInstance();
$sing->test();
$sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in
$sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from context
Copy after login

What is the significance of PHP implementing singleton mode:

It makes no sense, PHP has no thread concept and no asynchronous The code will not reside in memory, and all modifications can be controlled by oneself. There is no need to ensure that the class has only one instance. What is the point? You need to use singleton mode in the database connection class. What if some pages need to connect to two databases?

Is it really meaningless?

of course not.

Look at the code:

class A
{
    public function show()
    {
        echo "我是A类函数,要调用B类函数和C类函数<br/>";
        $b = new B();
        $b->show();
        $c = new C();
        $c->show(&#39;A&#39;);
    }
}
class B
{
    public function show()
    {
        echo "我是B类函数,要调用C类函数<br/>";
        $c = new C();
        $c->show(&#39;B&#39;);
    }
}
class C
{
    public function show($parm)
    {
        echo "我是C类函数,现在被{$parm}类函数调用<br/>";
    }
}
$a = new A();
$a->show();
Copy after login

During the call here, two class C objects are created. We know that new is a very resource-consuming operation. If class C here is a single In the example mode, just new once is enough. This idea is okay, but we usually use another method to do it:

class A
{
    public function show()
    {
        echo "我是A类函数,要调用B类函数和C类函数<br/>";
        $b = Unit::getInstance(&#39;B&#39;);
        $b->show();
        $c = Unit::getInstance(&#39;C&#39;);
        $c->show(&#39;A&#39;);
    }
}
class B
{
    public function show()
    {
        echo "我是B类函数,要调用C类函数<br/>";
        $c = Unit::getInstance(&#39;C&#39;);
        $c->show(&#39;B&#39;);
    }
}
class C
{
    public function __construct()
    {
        echo "C类对象被创建<br/>";
    }
    public function show($parm)
    {
        echo "我是C类函数,现在被{$parm}类函数调用<br/>";
    }
}
class Unit
{
    static public function getInstance($class)
    {
        static $arr = null;
        if (!isset($arr[$class]) || !$arr[$class] instanceof $class) {
            $arr[$class] = new $class();
        }
        return $arr[$class];
    }
}
$a = new A();
$a->show();
Copy after login

You can see when executing the code that the C class is only instantiated once, and then actually During operation, we generally use static variables to save objects and implement singleton mode in disguise.

The difference between the singleton mode and the use of static variables to implement a singleton:

The singleton mode forces a class to only create one object, which is generally displayed in a safe or unified interface It will be used sometimes, and the purpose of implementing singletons for static variables is mainly to reduce new operations, but it does not prevent new and clone operations.

Related learning recommendations: php programming (video)

The above is the detailed content of How to implement singleton mode in php. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles