Caching results in a PHP function

If you have a function that will get called lots of times, and you'd like to cache the results so as not to incur a performance penalty for hitting the disk/DB again use static variables.

function get_user($id) {
  // Sanitize the input
  $id = intval($id);

  // Declaring as static prevents the variable from dying when the function exits
  static $cache;

  // If the data is already in the cache just return that
  if ($cache[$id]) { return $cache[$id]; }

  // Get the data from the DB/Disk/Slow Source
  $rs = mysql_query("SELECT * FROM UserTable WHERE ID = $id");
  $ret = mysql_fetch_assoc($rs);

  // Store the results in the cache so it will be there next time
  $cache[$id] = $ret;

  return $ret;
}

This will store the results in cache (memory), speeding up subsequent requests. This cache will last until your script ends. To store across multiple script executions you'll want to look at something like memcache.



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.145.8.139
To prevent spam please submit by clicking the kitten: