Creating the Singleton design pattern in PHP5

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

How would one create a Singleton class using PHP5 classes?

21条回答
  •  心在旅途
    2020-11-22 05:09

    /**
     * Singleton class
     *
     */
    final class UserFactory
    {
        /**
         * Call this method to get singleton
         *
         * @return UserFactory
         */
        public static function Instance()
        {
            static $inst = null;
            if ($inst === null) {
                $inst = new UserFactory();
            }
            return $inst;
        }
    
        /**
         * Private ctor so nobody else can instantiate it
         *
         */
        private function __construct()
        {
    
        }
    }
    

    To use:

    $fact = UserFactory::Instance();
    $fact2 = UserFactory::Instance();
    

    $fact == $fact2;

    But:

    $fact = new UserFactory()
    

    Throws an error.

    See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null; works.

提交回复
热议问题