If the result of makeArray() will not change during one run of your script, consider caching its result in the static property of the class after the first retrieval. To do this, check if the variable is empty. If so, do the database action and save the result. If not empty, just return the existing array.
// A static property to hold the array private static $array; private static function makeArray() { // Only if still empty, populate the array if (empty(self::$array)) { // grab information from database and format array here self::$array = array(...); } // Return it - maybe newly populated, maybe cached return self::$array; }
You can even add a boolean parameter to a function that forces a new copy of the array.
// Add a boolean param (default false) to force fresh data private static function makeArray($fresh = false) { // If still empty OR the $fresh param is true, get new data if (empty(self::$array) || $fresh) { // grab information from database and format array here self::$array = array(...); } // Return it - maybe newly populated, maybe cached return self::$array; }
All of your other class methods may continue to call self::makeArray() , as you have already done.
public static function doSomething(){ $data = self::makeArray(); return $data->stuff; }
If you have added an optional fresh parameter and want to force the extract from the database
public static function doSomething(){ // Call normally (accepting cached values if present) $data = self::makeArray(); return $data->stuff; } public static function doSomethingRequiringRefresh(){ // Call with the $fresh param true $data = self::makeArray(true); return $data->stuff; }
source share