📜  PHP Memcached add()函数

📅  最后修改于: 2022-05-13 01:56:45.415000             🧑  作者: Mango

PHP Memcached add()函数

Memcached::add()函数是PHP中 memcached 类的内置函数,用于在 memcache 服务器上设置/添加具有过期时间 (TTL) 的给定值下的给定值。此函数类似于 Memcached::set()函数,但如果服务器上已存在密钥,则操作失败。

句法:

public Memcached::add( $key,  $value,  $expiration = ?): bool

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

  • key:存储值的键。
  • value:要存储的值。
  • expire:过期时间,默认为 0。更多信息见过期时间。

返回值:如果键值对存储成功,此函数返回 true,如果失败,则返回 false。如果键已经存在,Memcached::getResultCode()函数将返回 Memcached::RES_NOTSTORED。

下面的示例说明了PHP中的 Memcached::add()函数:

示例 1:

PHP
";
  
// 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);
  
?>


PHP
";
  
// 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);
  
?>


输出:

示例 2(已经存在的密钥对):

PHP

";
  
// 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);
  
?>

输出:

参考: https://www. PHP.net/manual/en/memcached.add。 PHP