Memcached::get
(PECL memcached >= 0.1.0)
Memcached::get — 检索一个元素
说明
Memcached::get()返回之前存储在key
下的元素。如果元素被找到,并且提供
了cas_token
参数, 这个参数(译注:这个参数在函数定义中是引用参数,用来传出元素的版本标记,原理
可以查阅乐观锁资料)将会包含该元素的CAS标记值。关于CAS标记值的使用,请查看Memcached::cas()的说明。
另外,可以通过cache_cb
参数设置Read-through caching callback。
参数
-
key
-
要检索的元素的key。
-
cache_cb
-
通读缓存回掉函数或
null
. -
cas_token
-
检索的元素的CAS标记值。
返回值
返回存储在服务端的元素的值或者在其他情况下返回false
。
如果key不存在,Memcached::getResultCode()返回Memcached::RES_NOTFOUND
。
范例
示例 #1 Memcached::get() 示例 #1
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->set('foo', 100);
var_dump($m->get('foo'));
?>
以上例程会输出:
int(100)
示例 #2 Memcached::get() 示例 #2
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
if (!($ip = $m->get('ip_block'))) {
if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
$ip = array();
$m->set('ip_block', $ip);
} else {
/* log error */
/* ... */
}
}
?>
参见
- Memcached::getByKey() - 从特定的服务器检索元素
- Memcached::getMulti() - 检索多个元素
- Memcached::getDelayed() - 请求多个元素

User Contributed Notes 3 notes
letynsoft at gmail dot com ¶
5 years ago
As of some version of php7 (i was not able to determine which exactly).
The $cas_token is no longer valid argument. It has been removed in favor of flags argument, as it appears to be causing issues when subclassing the Memcached class.
See https://github.com/php-memcached-dev/php-memcached/pull/214 for more details.
Basically you need to
<?php
function memcacheGet($key, $cb = null, &$cas = null) {
$m = memcacheGetObject();
if(empty($m))
return false;
if(defined('Memcached::GET_EXTENDED')) {
//Incompatible change in php7, took me 2 hours to figure this out, grrr
$_o = $m->get($key, $cb, Memcached::GET_EXTENDED);
$o = $_o['value'];
$cas = $_o['cas'];
} else {
$o = $m->get($key, $cb, $cas);
}
return $o;
}
?>
miha at hribar dot info ¶
12 years ago
This method also returns false in case you set the value to false, so in order to have a proper fault mechanism in place you need to check the result code to be certain that a key really does not exist in memcached.
<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key')); // boolean false
var_dump($Memcached->getResultCode()); // int 0 which is Memcached::RES_SUCCESS
?>
Or just make sure the values are not false :)
denis_truffaut[A-T]hotmail[D-O-T]com ¶
11 years ago
Note that this function can return NULL as FALSE, so don't make checks with === FALSE as with the old Memcache class, because it won't work. :O
Use the not (!) operator and check the result code with getResultCode() as mentioned in the documentation :)