Creating the Singleton design pattern in PHP5

前端 未结 21 2057
猫巷女王i
猫巷女王i 2020-11-22 04:21

How would one create a Singleton class using PHP5 classes?

21条回答
  •  醉梦人生
    2020-11-22 04:50

    PHP 5.3 allows the creation of an inheritable Singleton class via late static binding:

    class Singleton
    {
        protected static $instance = null;
    
        protected function __construct()
        {
            //Thou shalt not construct that which is unconstructable!
        }
    
        protected function __clone()
        {
            //Me not like clones! Me smash clones!
        }
    
        public static function getInstance()
        {
            if (!isset(static::$instance)) {
                static::$instance = new static;
            }
            return static::$instance;
        }
    }
    

    This solves the problem, that prior to PHP 5.3 any class that extended a Singleton would produce an instance of its parent class instead of its own.

    Now you can do:

    class Foobar extends Singleton {};
    $foo = Foobar::getInstance();
    

    And $foo will be an instance of Foobar instead of an instance of Singleton.

提交回复
热议问题