3

我有一个从数据库运行查询的功能。然后,它将被其他 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() 被调用两次。我猜它会在每次调用函数时执行查询工作,除非结果被缓存。如果我错了,有人会纠正我吗?

4

5 回答 5

3

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

于 2012-08-05T08:40:20.697 回答
2

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

class checkSomethingOrOther
{
    public $myVariable;

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

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

于 2012-08-05T08:50:34.660 回答
0

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

于 2012-08-05T08:41:00.117 回答
0

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

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

除非你实现一些缓存机制。

于 2012-08-05T08:41:41.570 回答
0

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

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

代码:

$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
}
于 2012-08-05T09:04:41.370 回答