Singleton pattern in php

前端 未结 4 1099
-上瘾入骨i
-上瘾入骨i 2020-12-10 21:04
class SingleTon
{
    private static $instance;

    private function __construct()
    {
    }

    public function getInstance() {
        if($instance === null) {         


        
4条回答
  •  鱼传尺愫
    2020-12-10 21:42

    A few corrections to your code. You need to ensure that the getInstance method is 'static', meaning it's a class method not an instance method. You also need to reference the attribute through the 'self' keyword.

    Though it's typically not done, you should also override the "__clone()" method, which short circuits cloning of instance.

    
    
    $mySingleton = Singleton::getInstance();
    

    One thing to not is that if you plan on doing unit testing, using the singleton pattern will cause you some difficulties. See http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html

提交回复
热议问题