略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Memcached::get

2024-03-28

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get检索一个元素

说明

public Memcached::get(string $key, callback $cache_cb = ?, float &$cas_token = ?): mixed

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

参见

add a noteadd a note

User Contributed Notes 3 notes

up
10
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;
}
?>
up
10
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 :)
up
-2
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 :)

官方地址:https://www.php.net/manual/en/memcached.get.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3