I’ve figured out a way to cache data (so that I won’t have to re-access the database when the same data has already been fetched before), and I do it by using a static variable inside a function:
function get_user( $id, $flush=false ){
static $cache;
if ( isset($cache[$id]) && !$flush )
return $cache[$id];
// Do something here to get user information
$user_info = $value;
// Return value after storing data into cache
return $cache[$id] = $user_info;
}
I’m not really sure if this is a good idea or maybe there’s a better way to do caching. Is this a fine method or not? If not, then what are the disadvantages?
have a look here. There are several solutions described. The type of the cache depents on how long you need to cache the data. Static variables are not shared between PHP processes and only can be cached for a short time – spanning script execution lifetime.