Note that there are some explanatory texts on larger screens.

plurals
  1. POShare variables between functions in PHP without using globals
    primarykey
    data
    text
    <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>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload