Static variables in PHP functions

Today I had to pull an identifying array from a DB to be used by an inner loop to apply categories to some book details I was parsing. Clearly I wanted to build this array once so it had to be built outside of the loop, but the inner loop was a function and there was something cloying about passing the to the inner function by reference everytime.

Recently I read some PHP books, and remembered that the static keyword can be used in a normal funciton, outside of a class. It seemed appropriate, but static variables can only be initialised to constants or literals. But this seems to do the job:

function parseData($data) {
	static $categories = array();
	if (empty($categories)) {
		$categories = getCategories();

I’m still not sure whether this is a good thing or not, but it’s good enough for now.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>