Share variables between functions in PHP without using globals

后端 未结 4 1353
余生分开走
余生分开走 2021-01-03 05:49

I have a class for interacting with a memcache server. I have different functions for inserting, deleting and retrieving data. Originally each function made a call to

4条回答
  •  伪装坚强ぢ
    2021-01-03 06:17

    I think you're looking for static properties here.

    class mc {
        private static $instance;
    
        public static function getInstance() {
            if (self::$instance== null) {
                self::$instance= new self;
            }
            return self::$instance;
        }
    
        private function __construct() {
            $this->mem = memcache_connect(...);
        }
    }
    

    This implements a basic singleton pattern. Instead of constructing the object call mc::getInstance(). Have a look at singletons.

提交回复
热议问题