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).
Memcache::increment
(PECL memcache >= 0.2.0)
Memcache::increment — Incrément la valeur d'un élément
Description
$key
[, int $value = 1
] )
Memcache::increment() incrémente la valeur d'un élément
identifié par la clé key par la valeur
value. Si l'élément identifié par la clé
key n'est pas de type numérique et ne peut
être converti en nombre, la valeur de cette élément sera défini à
value.
Memcache::increment() ne crée pas
un élément s'il n'existe pas.
Vous pouvez également utiliser la fonction memcache_increment().Note:
N'utilisez pas memcache::increment() avec les éléments stockés compressés. Dans ce cas, l'appel à la fonction Memcache::get() échouera.
Liste de paramètres
-
key -
Clé de l'élément à incrémenter.
-
value -
Incrémente l'élément par
value.
Valeurs de retour
Retourne la valeur du nouvel élément en cas de succès ou FALSE si une erreur survient.
Exemples
Exemple #1 Exemple avec Memcache::increment()
<?php
/* API procédurale */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* incrémentation du compteur de 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);
/* API orientée objet */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* incrémentation du compteur de 3 */
$current_value = $memcache_obj->increment('counter', 3);
?>
Voir aussi
- Memcache::decrement() - Décrémente la valeur d'un élément
- Memcache::replace() - Remplace une valeur d'un élément existant
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.
