search
HomeBackend DevelopmentPHP ProblemHow to implement singleton mode in php

How to implement singleton mode in php

Aug 06, 2020 pm 02:07 PM
phpSingleton 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

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();

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();

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
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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version