PHP Conference Nagoya 2025

Memcache::increment

(PECL memcache >= 0.2.0)

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

说明

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

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

注意:

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

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

参数

key

将要增加值的元素的 key。

value

参数 value 表明要将指定元素值增加多少。

返回值

成功时返回新的元素值 或者在失败时返回 false

示例

示例 #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);

?>

参见

添加备注

用户贡献的备注 5 notes

up
8
jay dot paroline at escapemg dot com
15 years ago
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.
up
2
Anonymous
15 years ago
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.
up
0
perroazul64 at gmail dot com
13 years ago
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).
up
0
ian at blip dot fm
15 years ago
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.
up
-1
Anonymous
19 years ago
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.
To Top