title: Share variables between functions in PHP without using globals
body: <p>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 <code>memcache_connect()</code>, however that was unnecessary, e.g.:</p>
  
  <pre><code>mc-&gt;insert()  
  mc-&gt;get()  
  mc-&gt;delete() 
  </code></pre>
  
  <p>would make three memcache connections. I worked around this by creating a construct for the class:</p>
  
  <pre><code>function __construct() {
      $this-&gt;mem = memcache_connect( ... );
  }
  </code></pre>
  
  <p>and then using <code>$this-&gt;mem</code> wherever the resource was needed, so each of the three functions use the same <code>memcache_connect</code> resource.</p>
  
  <p>This is alright, however if I call the class inside other classes, e.g.:</p>
  
  <pre><code>class abc
  {
      function __construct() {
          $this-&gt;mc = new cache_class;
      }
  }    
  class def
  {
      function __construct() {
          $this-&gt;mc = new cache_class;
      }
  }
  </code></pre>
  
  <p>then it is still making two <code>memcache_connect</code> calls, when it only <em>needs</em> one.</p>
  
  <p>I can do this with globals but I would prefer not to use them if I don't have to.</p>
  
  <p>Example globals implementation:</p>
  
  <pre><code>$resource = memcache_connect( ... );
  
  class cache_class
  {
      function insert() {
          global $resource;
          memcache_set( $resource , ... );
      }
      function get() {
          global $resource;
          return memcache_get( $resource , ... );
      }
  
  }
  </code></pre>
  
  <p>Then no matter how many times the class is called there will only be one call to <code>memcache_connect</code>.</p>
  
  <p>Is there a way to do this or should I just use globals?</p>