static variables and caching

August 24, 2008 – 1:11 pm

If you’re working with classes a lot, you’ve probably come across the “static” keyword for properties and methods, enabling you to call these members straight on the class itself, without instantiating an object.


class UserPeer
{
protected static $userlist;

public static function getUserList()
{
return self::$userlist;
}
}
What’s a little less frequently encountered is a static variable inside a function (or a method for that matter). Say you have a function that returns something rather computing-intensive, but that’s called multiple times from different areas and you don’t want to re-compute every time, and you also don’t want to drag a global variable around.. then static is for you. Check this out:


function get_world_formula()
{
static $result;
if(!$result)
{
$result = //compute complex stuff here;
}
return $result;
}

Voila! A self-contained caching function. Obviously $result persists only for the duration of one request, but that’ll do just fine if it cuts down some CPU cycles. (It does add to the memory usage though, so be selective where you use it.) If you want to take this one step further, you can make caching optional by adding an extra parameter.


function get_world_formula($use_cache = true)
{
static $result;
if(!$result || !$use_cache)
{
$result = //compute complex stuff here;
}
return $result;
}

That’s it. Small but cute.

A word of OOP caution! I would not recommend using this approach in objects-methods, because this one static variable would be the same accross all object instances, so all objects would return the same data the first method call yielded, and this may not be appropriate for other objects. Use object properties instead to store chached results.


Filed under: Rnadom Sftuf — by Richtermeister

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress