• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • Memcache::increment()

    (PECL memcache >= 0.2.0)

    增加一个元素的值

    说明

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

    参见

    • Memcache::decrement() 减小元素的值
    • Memcache::replace() 替换已经存在的元素的值
    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.
    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.
    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.