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 🙂
Yes, you can do that. It is supported as of PHP 5.0.0.
To clarify I would like to distinguish between two very different things in PHP that both use the static keyword. First, is the class static scope, which belongs specifically to the entire class. Second, is the variable static scope, which specifically belongs to the local scope of a function.
This is the class static scope (this is available only in PHP >= 5.3.0):
The above code would give you
int(1) int(2)which is what you are expecting.This is the variable static scope (this is available in PHP >= 5.0.0):
The above code would also give you
int(1) int(2)which is also what you are expecting.Notice that one belongs specifically to the function’s local scope (even if that function is a class member) and the other belongs specifically to the class.
Also notice I used the static keyword in my first example and not the self keyword, since self does not allow you to do LSB (Late Static Binding). This is likely something you’re going to need to take into consideration when you’re inheriting and then calling on the parent class and especially if you’re going to be using class static variables and not static variables in the function’s local scope.