有没有更简单的方法来使用静态变量来做到这一点?
Is there an easier way to do this with static variables?
我有一些旧代码,我在其中使用了这样的函数:
function getDataPlain() {
$theArray = fetchFromDb("select * from tablename");
return $theArray;
}
并像这样将它们转换为使用静态:
function getDataStaticVersion() {
static $theArray;
if (isset($theArray)) {
return $theArray;
}
else {
$theArray = fetchFromDb("select * from tablename");
return $theArray;
}
}
然后,如果多次调用该方法,它只会访问数据库一次。这很好用,但我想知道是否有一种更简洁的方法可以用更少的代码在每个函数中编写。 (我有很多这样的函数,我想转换成静态版本)
您可以使用未设置静态变量和空合并加载值的事实...
function getDataStaticVersion() {
static $theArray;
return $theArray ?? $theArray = fetchFromDb("select * from tablename");
}
因此,如果未设置,它将 运行 fetchFromDb()
。
作为替代方案,您可以稍微重组代码,而不是之前的 return,您可以在设置数组时调用额外的代码,并且始终在末尾调用 return。 .
function getDataStaticVersion() {
static $theArray;
if (! isset($theArray)) {
$theArray = fetchFromDb("select * from tablename");
}
return $theArray;
}
我有一些旧代码,我在其中使用了这样的函数:
function getDataPlain() {
$theArray = fetchFromDb("select * from tablename");
return $theArray;
}
并像这样将它们转换为使用静态:
function getDataStaticVersion() {
static $theArray;
if (isset($theArray)) {
return $theArray;
}
else {
$theArray = fetchFromDb("select * from tablename");
return $theArray;
}
}
然后,如果多次调用该方法,它只会访问数据库一次。这很好用,但我想知道是否有一种更简洁的方法可以用更少的代码在每个函数中编写。 (我有很多这样的函数,我想转换成静态版本)
您可以使用未设置静态变量和空合并加载值的事实...
function getDataStaticVersion() {
static $theArray;
return $theArray ?? $theArray = fetchFromDb("select * from tablename");
}
因此,如果未设置,它将 运行 fetchFromDb()
。
作为替代方案,您可以稍微重组代码,而不是之前的 return,您可以在设置数组时调用额外的代码,并且始终在末尾调用 return。 .
function getDataStaticVersion() {
static $theArray;
if (! isset($theArray)) {
$theArray = fetchFromDb("select * from tablename");
}
return $theArray;
}