Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  故里飘歌
    2020-11-22 04:51

    I agree with the first answer but I would also declare the class as final so that it cannot be extended as extending a singleton violates the singleton pattern. Also the instance variable should be private so that it cannot be accessed directly. Also make the __clone method private so that you cannot clone the singleton object.

    Below is some example code.

    /**
     * Singleton class
     *
     */
    final class UserFactory
    {
        private static $_instance = null;
    
        /**
         * Private constructor
         *
         */
        private function __construct() {}
    
        /**
         * Private clone method
         *
         */
         private function __clone() {}
    
        /**
         * Call this method to get singleton
         *
         * @return UserFactory
         */
        public static function getInstance()
        {
            if (self::$_instance === null) {
                self::$_instance = new UserFactory();
            }
            return self::$_instance;
        }
    }
    

    Example Usage

    $user_factory = UserFactory::getInstance();
    

    What this stops you from doing (which would violate the singleton pattern..

    YOU CANNOT DO THIS!

    $user_factory = UserFactory::$_instance;
    
    class SecondUserFactory extends UserFactory { }
    

提交回复
热议问题