Extending singletons in PHP

前端 未结 6 704
春和景丽
春和景丽 2021-01-30 11:28

I\'m working in a web app framework, and part of it consists of a number of services, all implemented as singletons. They all extend a Service class, where the singleton behavio

6条回答
  •  不知归路
    2021-01-30 12:01

    Had I paid more attention in 5.3 class, I would have known how to solve this myself. Using the new late static binding feature of PHP 5.3, I believe Coronatus' proposition can be simplified into this:

    class Singleton {
        protected static $instance;
    
        protected function __construct() { }
    
        final public static function getInstance() {
            if (!isset(static::$instance)) {
                static::$instance = new static();
            }
    
            return static::$instance;
        }
    
        final private function __clone() { }
    }
    

    I tried it out, and it works like a charm. Pre 5.3 is still a whole different story, though.

提交回复
热议问题