14

Can you store complex objects including public/static variables/functions self-defined/inherited?

I am talking about Memcached ( http://memcached.org/ )

Octavian
  • 4,519
  • 8
  • 28
  • 39
  • Only if they're serialized; and the class must have been included/defined before you can unserialize again – Mark Baker May 29 '13 at 09:17
  • If you want to serialize closures, then you'll need something like https://github.com/jeremeamia/super_closure – Mark Baker May 29 '13 at 09:19

1 Answers1

15

use http://php.net/manual/en/function.serialize.php

<?php

// connect memcache
$memcache_obj = new Memcache;
$memcache_obj->connect('localhost', 11211);

// simple example class
class MyClass {
    private $var = 'default';

    public function __construct($var = null) {
        if ($var) {
            $this->setVar($var);
        }
    }

    public function getVar() {
        return $this->var;
    }

    public function setVar($var) {
        $this->var = $var;
    }
}

$obj1 = new MyClass();
$obj2 = new MyClass('test2');
$obj3 = new MyClass();
$obj3->setVar('test3');

// dump the values using the method getVar
var_dump($obj1->getVar(), $obj2->getVar(), $obj3->getVar());

// store objects serialized in memcache, set MEMCACHE_COMPRESSED as flag so it takes less space in memory
$memcache_obj->set('key1', serialize($obj1), MEMCACHE_COMPRESSED);
$memcache_obj->set('key2', serialize($obj2), MEMCACHE_COMPRESSED);
$memcache_obj->set('key3', serialize($obj3), MEMCACHE_COMPRESSED);

// unset the objects to prove it ;-)
unset($obj1, $obj2, $obj3);

// get the objects from memcache and unserialze
// IMPORTANT: THE CLASS NEEEDS TO EXISTS! 
// So if you have MyClass in some other file and include it, it has to be included at this point
// If you have an autoloader then it will work easily ofcourse :-)
$obj1 = unserialize($memcache_obj->get('key1'));
$obj2 = unserialize($memcache_obj->get('key2'));
$obj3 = unserialize($memcache_obj->get('key3'));

// dump the values using the method getVar
var_dump($obj1->getVar(), $obj2->getVar(), $obj3->getVar());

?>
Ruben de Vries
  • 535
  • 5
  • 14
  • isn't it possible to set `Memcached::OPT_SERIALIZER` to `Memcached::SERIALIZER_PHP` as described here: https://www.php.net/manual/en/memcached.constants.php ? So an explicit `(un)serialize()` shouldn't be necessary? – emfi Mar 27 '19 at 12:38
  • @emfi ye, it appears it's even set by default in modern PHP versions! personally I'd still prefer explicitly doing the `serialize` as it makes it clear to the reader what is happening, but it should work fine and it would be extremely unlikely they'd break backwards compatibility. – Ruben de Vries May 29 '19 at 08:14
  • how about json_encode and json_decode instead of serialize and unserialize? – Eryk Wróbel Aug 27 '20 at 10:18