多次从函数获取结果可能会导致此函数再次执行查询


Get result from a function more than once may cause this function to do query again?

我有一个从数据库运行查询的函数。然后,它将被其他 2 个函数调用。

function query(){
 $query= // get data from database;
return $query;
}
function show_something(){
$data = query();
//do something
}
function show_else(){
$data = query();
//do something else
}

函数 query() 被调用两次。我想每次调用函数时它都会执行查询工作,除非缓存结果。如果我错了,有人会纠正我吗?

是的,它将被调用两次。如果需要,可以使用静态变量缓存结果。

如果您希望每次都拉取相同的查询(即,没有变量更改),则最好使用以下对象:

class checkSomethingOrOther
{
    public $myVariable;
    public function __get($name)
    {
        if (!array_key_exists($name, $this->myVariable))
        {
            $this->myVariable=query();
        }
        return $this-myVariable;
    }
}

这将简单地检查变量是否设置,如果没有,它会抓取数据并返回它,否则,只是返回它。

你可以简单地做这样的事情:

  • 设置一个指示器以标记查询是第一个查询还是重复查询。
  • 查询前,请检查指标。

法典:

$fresh = true; // fresh results wanted
function query(){
global $fresh;
if($fresh){
     $query= // get data from database;
     $bar = $query; // cache the $query value for next uses..
     $$fresh = false; // set the indicator that query is cached.
}else{ // this is repeated query
    $query = $bar; //we had set the $bar last time
}
return $query;
}
function show_something(){
//first time query, $query will be fetched from database,
// also $fresh will be set to false
$data = query();
//do something
}
function show_else(){
//repeated query, cached value will be returned.
$data = query();
//do something else
}
$foo = true; // if you want fresh results, set $fresh to true before query
function show_fresh(){
//results will be fresh, because we have set $fresh to true again.
$data = query();
//do something else
}

不,这是正确的;你的函数无条件地执行显式查询,因此每次调用它时都会执行它。

数据库可能在函数调用之间发生了变化。 即使他们一个接一个地被立即调用。

所以,是的,查询将运行两次;因为结果可能不同。

除非您实现某种缓存机制。