CascadiaPHP 2024

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get检索元素

说明

public Memcached::get(string $key, ?callable $cache_cb = null, int $get_flags = 0): mixed

Memcached::get() 返回之前存储在 key 下的元素。如果元素被找到,并且 get_flags 指定为 Memcached::GET_EXTENDED,也会返回该元素的 CAS 记号。关于 CAS 记号的使用,参阅 Memcached::cas()。可以通过 cache_cb 参数指定 通读缓存回调

参数

key

要检索的元素的 key。

cache_cb

通读缓存回掉函数或 null

get_flags

flag 控制返回结果。当指定为 Memcached::GET_EXTENDED 时,该函数还将返回 CAS 记号。

返回值

返回存储在缓存中的值,否则返回 false。 如果 get_flags 设置为 Memcached::GET_EXTENDED,则返回包含值和 CAS 记号的数组,而不仅仅返回值。如果 key 不存在,Memcached::getResultCode() 将返回 Memcached::RES_NOTFOUND

更新日志

版本 说明
PECL memcached 3.0.0 移除 &cas_token 参数。 相反,添加 get_flags,当赋予 Memcached::GET_EXTENDED 的值时,将确保获取 CAS 记号。

示例

示例 #1 Memcached::get() 示例

<?php
$m
= new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

以上示例会输出:

int(100)

示例 #2 Memcached::get() 示例

<?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 */
/* ... */
}
}
?>

参见

add a note

User Contributed Notes 3 notes

up
12
letynsoft at gmail dot com
7 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;
}
?>
up
10
miha at hribar dot info
14 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 :)
up
-2
denis_truffaut[A-T]hotmail[D-O-T]com
13 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 :)
To Top