I'm working in PHP.
I have a function (F1) that gets called a variable amount of times. Within that function, I need to load a constant data set from another function (F2). It's always the same data set loaded, however loading the set involves some database lookups and processing. Rather than call F2 repeatedly and increase overhead/redundancy/processing requirements, I would like to put the result into a static variable in F1. However, for whatever reason, it will not allow me to set the variable as static using the function call.
A code example:
function calledRepeatedly() {
static $dataset = loadDataset();
// some minor processing here using the dataset
// and probably a loop
return "stuff";
}
function loadDataset() {
//intensive dataset load code
//plus a database lookup or two
//whatever else
return array(
"data1",
"data2"
);
}
The above does NOT work. It results in an error -- unexpected '(', expecting ',' or ';'.
I do realize that it would work, and it would be passed by reference thus eliminating overhead, however that involves the extra work of making sure that calls to calledRepeatedly actually have the dataset in the arguments list.
Is there any way to do this?
I'd throw the static declaration in loadDataset
. I've added a boolean to determine whether to refresh the data from the database. The basic process is as follows: Define the static variable, rather than setting it to something. Then check if it's set (or if $refresh
was set to true). If it's not, load the intensive data from the database.
function loadDataset($refresh = false) {
static $dataset;
if( !isset($dataset) || $refresh )
{
$dataset = array();
//intensive dataset load code
//plus a database lookup or two
//whatever else
}
return $dataset;
}
Edit: You can of course still use the static ... isset
pattern in your original function, but it seemed cleaner to put it in loadDataset
.
While you can't assign the result of a function directly to a static variable you can still capture the return value and assign to the static variable:
<?php
function calledRepeatedly() {
static $dataset = false;
if (!$dataset) {
echo "dataset is empty, fetching data\n";
$v = expensive();
$dataset = $v;
}
echo "$dataset\n";
}
function expensive() {
return 'complex data structure';
}
calledRepeatedly();
calledRepeatedly();
calledRepeatedly();
Output:
dataset is empty, fetching data
complex data structure
complex data structure
complex data structure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With