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).
(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
/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);
/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);
?>
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).
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.
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.
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.
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.