• PHP Video Tutorials

PHP - Memcache::set() Function



Memcache::set() function can store the data at the server.

Syntax

bool Memcache::set( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::set() function can store an item 'var' with a key on the Memcached server. Parameter expire is an expiration time in seconds. If it is 0, an item never expires (but the Memcached server doesn't guarantee this item to be stored all the time, it can be deleted from the cache to make a place for other items). We can use the MEMCACHE_COMPRESSED constant as a flag value if we want to use on-the-fly compression (uses zlib).

We can also use the memcache_set() function.

Memcache::set() function can return true on success or false on failure.

Example 1

<?php
   /* Procedural API */
   $memcache_obj = memcache_connect("memcache_host", 11211);  
   // connect to memcached server

   /* 
      set the value of an item with a key 'var_key' using 0 as flag value, 
      compression is not used expire time is 30 seconds 
   */
   memcache_set($memcache_obj, "var_key", "some variable", 0, 30);

   echo memcache_get($memcache_obj, "var_key");
?>

Example 2

<?php
   /* OO API */
   $memcache_obj = new Memcache;
   $memcache_obj->connect("memcache_host", 11211);  // connect to memcached server

   /*
      set value of item with key "var_key", using on-the-fly compression
      expire time is 50 seconds
   */
   $memcache_obj->set("var_key", "some really big variable", MEMCACHE_COMPRESSED, 50);

   echo $memcache_obj->get("var_key");
?>
Advertisements