gpt4 book ai didi

php - memcached可以存储复杂的对象吗?

转载 作者:行者123 更新时间:2023-12-02 22:33:47 26 4
gpt4 key购买 nike

你可以存储复杂的对象,包括公共(public)/静态变量/自定义/继承的函数吗?

我正在谈论 Memcached ( http://memcached.org/ )

最佳答案

使用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());

?>

关于php - memcached可以存储复杂的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16809953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com