通过调用另一个函数设置函数中的静态变量

Nat*_*iel 5 php variables static function call

我在PHP工作.

我有一个被称为可变次数的函数(F1).在该函数中,我需要从另一个函数(F2)加载一个常量数据集.它始终与加载的数据集相同,但加载集合涉及一些数据库查找和处理.我不是反复调用F2并增加开销/冗余/处理要求,而是将结果放入F1的静态变量中.但是,无论出于何种原因,它都不允许我使用函数调用将变量设置为静态.

一个代码示例:

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"
    );
}
Run Code Online (Sandbox Code Playgroud)

以上不起作用.它导致错误 - 意外'(',期待','或';'.

我确实认识到它会工作,并且它将通过引用传递,从而消除开销,但是这涉及额外的工作,以确保对来自calledRepeatedly的调用实际上在参数列表中具有数据集.

有没有办法做到这一点?

the*_*dow 11

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;
}
Run Code Online (Sandbox Code Playgroud)

Edit: You can of course still use the static ... isset pattern in your original function, but it seemed cleaner to put it in loadDataset.