Krysti.Engineer Official Chat
You are viewing an inferior version of the site because your browser does not support WebP. Do upgrade to something like Chrome or Firefox. Loading websites like this causes them to require a fallback set of images and they are almost always lower quality and larger in size.

Useful APCu Cache Function

2022-07-18T:00:00:00+00:00 July 18 2022 00:00:00

class KCache {
	private $data = array();
	public  $expiry;
	function __construct($exp = 30) {
		$this->expiry = intval($exp);
	public function __get($name) {
		if(apcu_exists($name)) {	return apcu_fetch($name); } 
		else { 
			if (array_key_exists($name, $this->data)) { return $this->data[$name]; } 
	public function __set($name, $value) {
		$this->data[$name] = $value;
		if(apcu_exists($name)) { /* */ } else { 
	public function __isset($name) {
		if(apcu_exists($name)) { return TRUE; } else { return FALSE; }
	public function __unset($name) {
			if(apcu_exists($name)) { apcu_delete($name); }

This class will allow you to juggle the APCu functions by just referencing and setting them like normal varables. If you're using PHP 5.x you might need to roll the functions in here back to reflect the prefix 'apc_' instead of 'apcu_' for it to work properly.

function someFunction() {
	return 31337;
$cache = new KCache();
if(isset($cache->test)) {
	$test = "From Cache: ". $cache->test;
} else {
	$cache->test = someFunction();
	$test = "Fetching: ". $cache->test;
echo $test;

This is a good function to store some small data you need but maybe requires more crunch than you'd like to see crunching every site load. Reload the example to see how it works after including the above class. You should see first that it fetched the information from the function then after reloading the page you have a cached value from that function.

Contact Krysti

@itskrystibitch Twitter Photo
Official Chat
Virtual Krysti
E-Mail / Notify of errors:
coder [@]
Please be patient contacting me, I don't really check much of social media or anything. If you use the IRC be sure to stick around because that's how IRC works, silly. :P