In C we can do (if I remember well) that :
void foo()
{
static bool firstCall = true;
if(firstCall)
{
// stuff to do on first call
firstCall = false;
}
// more stuff
}
I would like to do that in PHP to avoid my models to query the database more than once when the same method is called more than once.
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;
}
}
Is it allowed ? Does it work ? Is it compatible with PHP < 5.3 ?
If yes then i have another question :
Say we have several methods common to all models, i would group them in an abstract base class :
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;
}
}
Would this work too ? Could it be improved ?
Thanks for your help :)
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.