当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


PHP Memcached get()用法及代码示例


Memcached::get() 函数是 PHP 中 memcached 类的内置函数,用于获取存储在 memcache 服务器上的给定键下的值。

用法:

public Memcached::get( $key, 
    callable $cache_cb = ?,  $$flags = ?):mixed

参数:这个函数接受三个参数:

  • key:要检索的项目的键。
  • cache_cb:Read-through 缓存回调或空。
  • flags:用于控制返回结果的标志。当给定 Memcached::GET_EXTENDED 时,该函数还将返回 CAS 令牌。

返回值:返回存储在缓存中的值,否则返回 false。如果标志设置为 Memcached::GET_EXTENDED,则返回一个包含值和 CAS 令牌的数组,而不仅仅是返回值。如果键不存在,Memcached::getResultCode() 将返回 Memcached::RES_NOTFOUND。



以下示例程序旨在说明 PHP 中的 Memcached::set() 函数:

范例1:

PHP


<?php
  
echo "<pre>";
  
// Server & port details
$server = '127.0.0.1';
$port = 11211;
  
// Initiate a new object of memcache
$memcacheD = new Memcached();
  
// Add server
if ($memcacheD->addServer($server, $port)) {
    echo "**  server added ** \n";
}
else {
    echo "** issue while creating a server **\n";
}
  
// Set key & value with TTL
$key = "GEEKSFORGEEKS";
$value = "computer science portal";
$ttl = 3600;
  
if ($memcacheD->add($key, $value, $ttl)) 
    echo "** added key-value (" . $key . ":" 
    . $value . ")to cache successfully!! **\n";
      
else 
    echo "** error while adding value to cache!! **\n";
  
// Get value of key
echo "****   FETCHED VALUE   FOR KEY:" 
    . $key . " ****\n";
      
$valD = $memcacheD->get($key);
var_dump($valD);
  
?>

输出:

**  server added **
** added key-value (GEEKSFORGEEKS:computer science portal)to cache successfully!! **
****   FETCHED VALUE   FOR KEY:GEEKSFORGEEKS ****
string(23) “computer science portal”

示例 2(已存储键值):

PHP


<?php
echo "<pre>";
  
// Server & port details
$server = '127.0.0.1';
$port = 11211;
  
// Initiate a new object of memcache
$memcacheD = new Memcached();
  
// Add server
if ($memcacheD->addServer($server, $port)) {
    echo "**  server added ** \n";
}
else {
    echo "** issue while creating a server **\n";
}
  
// Set key & value with TTL
$key = "GEEKSFORGEEKS";
$value = "computer science portal";
$ttl = 3600;
  
if ($memcacheD->add($key, $value, $ttl)) 
      echo "** added key-value (" . $key . ":" 
      . $value . ")to cache successfully!! **\n";
else 
      echo "** error while adding value to cache!! **\n";
  
// Get value of key
echo "****   FETCHED VALUE   FOR KEY:"
      . $key . " ****\n";
  
$valD = $memcacheD->get($key);
var_dump($valD);
  
?>

输出:

**  server added **
** error while adding value to cache!!::MSG::NOT STORED **
****   FETCHED VALUE   FOR KEY:geeksforgeeks ****
string(23) “computer science portal”

参考: https://www.php.net/manual/en/memcached.get.php




相关用法


注:本文由纯净天空筛选整理自Shivam.Pradhan大神的英文原创作品 PHP Memcached get() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。