Share variables between functions in PHP without using globals

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

    You should use dependency injection. The singleton pattern and static constructs are considered bad practice because they essentially are globals (and for good reason -- they cement you to using whatever class you instantiate as opposed to some other).

    Here is something like what you should do in order to have easy maintenance.

    class MemCache {
        protected $memcache;
    
        public function __construct(){
            $this->memcache = memcache_connect();
        }
    }
    
    class Client {
        protected $MemCache;
    
        public function __construct( MemCache $MemCache ){
            $this->MemCache = $MemCache;
        }
    
        public function getMemCache(){
            return $this->MemCache;
        }
    }
    
    $MemCache = new MemCache();
    $Client = new Client($MemCache);
    $MemCache1 = $Client->getMemCache();
    
    // $MemCache and $MemCache1 are the same object. 
    // memcache_connect() has not been called more than once.
    
    0 讨论(0)
  • 2021-01-03 06:05

    Pass in the MC instance:

    class abc
    {
        function __construct($mc) {
            $this->mc = $mc;
        }
    }    
    class def
    {
        function __construct($mc) {
            $this->mc = $mc;
        }
    }
    
    $mc = new cache_class;
    $abc = new abc($mc);
    

    etc.

    0 讨论(0)
  • 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, ...)
    ...
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题