Memcache::increment

(PECL memcache >= 0.2.0)

Memcache::increment增加一个元素的值

说明

Memcache::increment ( string $key , int $value = 1 ) : int

Memcache::increment()将指定元素的值增加value。如果指定的key 对应的元素不是数值类型并且不能被转换为数值, 会将此值修改为value. Memcache::increment() 不会在key对应元素不存在时创建元素。

Note:

不要在经过压缩存储的元素上使用Memcache::increment(),因为这样作会导致后续对Memcache::get()的调用失败。

同样你也可以使用函数memcache_increment()

参数

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);

?>

参见

User Contributed Notes

perroazul64 at gmail dot com 07-Jun-2011 10:46
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).
ian at blip dot fm 30-Jun-2009 04:28
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.
jay dot paroline at escapemg dot com 13-May-2009 06:34
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.
Anonymous 13-May-2009 06:16
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.
15-Jun-2005 12:54
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.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有