Share variables between functions in PHP without using globals

后端 未结 4 1376
余生分开走
余生分开走 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条回答
  •  旧时难觅i
    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.
    

提交回复
热议问题