Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  攒了一身酷
    2020-11-22 05:07

    Unfortunately Inwdr's answer breaks when there are multiple subclasses.

    Here is a correct inheritable Singleton base class.

    class Singleton
    {
        private static $instances = array();
        protected function __construct() {}
        protected function __clone() {}
        public function __wakeup()
        {
            throw new Exception("Cannot unserialize singleton");
        }
    
        public static function getInstance()
        {
            $cls = get_called_class(); // late-static-bound class name
            if (!isset(self::$instances[$cls])) {
                self::$instances[$cls] = new static;
            }
            return self::$instances[$cls];
        }
    }
    

    Test code:

    class Foo extends Singleton {}
    class Bar extends Singleton {}
    
    echo get_class(Foo::getInstance()) . "\n";
    echo get_class(Bar::getInstance()) . "\n";
    

提交回复
热议问题