【发布时间】:2012-11-23 22:52:44
【问题描述】:
在 C 中,我们可以这样做(如果我没记错的话):
void foo()
{
static bool firstCall = true;
if(firstCall)
{
// stuff to do on first call
firstCall = false;
}
// more stuff
}
我想在 PHP 中这样做,以避免我的模型在多次调用同一方法时多次查询数据库。
class User
{
public static function & getAll($reload = false)
{
static $result = null;
if($reload && null === $result)
{
// query the database and store the datas in $result
}
return $result;
}
}
允许吗?行得通吗?是否与 PHP
如果是,那么我还有一个问题:
假设我们有几种所有模型共有的方法,我会将它们分组到一个抽象基类中:
abstract class AbstractModel
{
public static function & getAll($tableName, $reload = false)
{
static $result = array();
if($reload && !isset($result[$tableName]))
{
// query the database depending on $tableName,
// and store the datas in $result[$tableName]
}
return $result[$tableName];
}
}
class User extends AbstractModel
{
public static function & getAll($reload = false)
{
$result = parent::getAll('users', $reload);
return $result;
}
}
class Group extends AbstractModel
{
public static function & getAll($reload = false)
{
$result = parent::getAll('groups', $reload);
return $result;
}
}
这也行吗?可以改进吗?
感谢您的帮助:)
【问题讨论】:
-
无关:为什么要返回参考文献?你应该让PHP优化代码,你通常不需要这样做。
-
我通常返回数组,如果我理解得很好,它们被认为是原始类型,并被复制。我错了吗?
-
只要你不修改它,编译器就会优化它而不复制数组。
-
@JuanMendes 这是一个新功能吗?我也遇到了数组被复制的麻烦。您可以通过引用传递它们或将它们包装在一个类中来解决它。
-
见php.net/manual/en/language.references.return.php
Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.
标签: php function methods static