Memcached::add() 函数是 PHP 中 memcached 类的内置函数,用于在 memcache 服务器上设置/添加具有过期时间 (TTL) 的给定值下的给定值。此函数类似于 Memcached::set() 函数,但如果服务器上已存在 key ,则操作失败。
用法:
public Memcached::add( $key, $value, $expiration = ?):bool
参数:该函数接受三个参数:
- key:存储值的键。
- value:要存储的值。
- expiration:过期时间,默认为 0。有关更多信息,请参阅过期时间。
返回值:如果键值对存储成功,此函数返回 true,如果失败则返回 false。如果键已经存在,则 Memcached::getResultCode() 函数将返回 Memcached::RES_NOTSTORED。
下面的例子说明了 PHP 中的 Memcached::add() 函数:
范例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(已经存在的 key-pair):
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.add.php
相关用法
- PHP Memcached::getServerList()用法及代码示例
- PHP Memcached get()用法及代码示例
- PHP Memcached addServer()用法及代码示例
- PHP Ds\Set add()用法及代码示例
- PHP SplDoublyLinkedList add()用法及代码示例
- PHP IntlCalendar add()用法及代码示例
- PHP DateTime add()用法及代码示例
- PHP DateTimeImmutable add()用法及代码示例
- d3.js d3.set.add()用法及代码示例
- Tensorflow.js tf.layers.add()用法及代码示例
注:本文由纯净天空筛选整理自Shivam.Pradhan大神的英文原创作品 PHP Memcached add() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。