0

The following code works fine:

$memcached = new Memcached();
$memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
$memcached->setOption(Memcached::OPT_DYNAMIC_POLLING_INTERVAL_SECS, 60);    
$memcached->addServer('etc.expalp.cfg.apse1.cache.amazonaws.com', 11211);

$memcached->set('tester', 'set tester...babe!!', 600);
echo $memcached->get('tester');

I want to however move the creation of the object into a Class (because there are quite a few more settings that are set and I don't want this included on every page). I tried the following but it doesn't work:

$elasticache = new elasticache();
$elasticache->memcached->set('tester', 'set tester...babe!!', 600);
echo $elasticache->memcached->get('tester');

Then I have a class called elasticache (loaded with spl_autoload_register) as below:

class elasticache {

  function __construct() {
    $memcached = new Memcached();   
    $memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
    $memcached->setOption(Memcached::OPT_DYNAMIC_POLLING_INTERVAL_SECS, 60);
    $memcached->addServer('etc.expalp.cfg.apse1.cache.amazonaws.com', 11211);
  }

}

The fails to work so obviously I'm doing something wrong here. Note: Memcached() object is a PHP dynamic library - note that this really matters). Anyone have any ideas - first time I've tried this.

1 Answer 1

2

$memcached is a local variable in a class method, which will be out of scope once the method exits; $this->memcached would be a class property that exists as long as an object of that class exists

class elasticache {
  public $memcached;

  function __construct() {
    $this->memcached = new Memcached();   
    $this->memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
    $this->memcached->setOption(Memcached::OPT_DYNAMIC_POLLING_INTERVAL_SECS, 60);
    $this->memcached->addServer('etc.expalp.cfg.apse1.cache.amazonaws.com', 11211);
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

thankyou - just had to change private $memcached to public so I could access it outside the class - cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.