Adam
Adam

Reputation: 20882

PHP Object within Object

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.

Upvotes: 0

Views: 382

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

$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);
  }

}

Upvotes: 2

Related Questions