Static variable in a function specified by calling another function

I work in PHP.

I have a function (F1) called a variable number of times. Inside this function, I need to load a constant data set from another function (F2). It always loads the same data set, however loading the set involves some searches and database processing. Instead of calling F2 multiple times and increasing the overhead / overhead / processing requirements, I would like to cast the result into a static variable in F1. However, for some reason, it will not allow me to set the variable as static by calling a function.

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. This results in an error - unexpected '(', waiting for ',' or ';'.

, , , , , , Roupeatedly .

?

+5
3

loadDataset. , , . : , . , ( $refresh true). , .

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;
}

: , , - static ... isset , , loadDataset.

+11

, :

<?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();

:

dataset is empty, fetching data
complex data structure
complex data structure
complex data structure
+3

As @Mark comments, you cannot assign an expression to a static variable. Instead of trying to use static variables, the best solution is to use some kind of caching mechanism, such as APC, to store the result.

0
source

All Articles