Share variables between functions in PHP without using globals

后端 未结 4 1372
余生分开走
余生分开走 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:08

    I would code another class using singleton pattern for getting the only instance of memcache. Like this -

    class MemCache 
    { 
      private static $instance = false;   
      private function __construct() {}
    
      public static function getInstance()
      { 
        if(self::$instance === false)
        { 
          self::$instance = memcache_connect(); 
        } 
    
        return self::$instance; 
      } 
    }
    

    and usage -

    $mc = MemCache::getInstance();
    memcache_get($mc, ...)
    ...
    

提交回复
热议问题