©
このドキュメントでは、 php中国語ネットマニュアル リリース
(PECL memcache >= 0.2.0)
Memcache::increment — 增加一个元素的值
$key
[, int $value
= 1
] ) Memcache::increment() 将指定元素的值增加value
。如果指定的key
对应的元素不是数值类型并且不能被转换为数值, 会将此值修改为value
.
Memcache::increment() 不会在key对应元素不存在时创建元素。
同样你也可以使用函数 memcache_increment() 。Note:
不要在经过压缩存储的元素上使用 Memcache::increment() ,因为这样作会导致后续对 Memcache::get() 的调用失败。
key
将要增加值的元素的key。
value
参数value
表明要将指定元素值增加多少。
成功时返回新的元素值 或者在失败时返回 FALSE
Example #1 Memcache::increment() 示例
<?php
$memcache_obj = memcache_connect ( 'memcache_host' , 11211 );
$current_value = memcache_increment ( $memcache_obj , 'counter' , 2 );
$memcache_obj = new Memcache ;
$memcache_obj -> connect ( 'memcache_host' , 11211 );
$current_value = $memcache_obj -> increment ( 'counter' , 3 );
?>
[#1] perroazul64 at gmail dot com [2011-06-07 10:46:18]
When the key doesn't exist it may return either bool(false) or int(0) (I get different return values on different servers), so be careful if you check for something like ($memcache->increment($key) === false).
[#2] ian at blip dot fm [2009-06-30 16:28:46]
Be careful to use Memcache::decrement() and never Memcache::increment() with a negative value.
The check that prevents Memcache::decrement() from going negative is not in place with Memcache::increment(), so you can end up with a garbage integer on the order of 18 quintillion stored in place of the expected value.
[#3] jay dot paroline at escapemg dot com [2009-05-13 06:34:21]
Instead of checking the value before incrementing, you can simply ADD it instead before incrementing each time. If it's already there, your ADD is ignored, and if it's not there, it's set.
If you add($memcacheKey, 0) and then increment($memcacheKey, 1) in that order, you avoid all possible race conditions. If two threads are running this code concurrently, you will always end up with your value being 2 no matter which order the threads execute in.
[#4] Anonymous [2009-05-13 06:16:29]
Please note:
If the key does not exist, memcache does NOT return false (as you might expect) but 0.
You won't get any hint that the key did not exist and still does not exist and that nothing was incremented.
[#5] [2005-06-15 12:54:16]
if no variable exists, even if you specify an increment value, the result will be null.
if you're using this for a mutex, chk if its null, and if so, then ADD the variable.