Using static in PHP
- by nischayn22
I have a few functions in PHP that read data from functions in a class
readUsername(int userId){
$reader = getReader();
return $reader->getname(userId);
}
readUserAddress(){
$reader = getReader();
return $reader->getaddress(userId);
}
All these make a call to
getReader()
{
require_once("Reader.php");
static $reader = new Reader();
return $reader;
}
An overview of Reader
class Reader{
getname(int id)
{
//if in-memory cache exists for this id return that
//else get from db and cache it
}
getaddress(int id)
{
$this->getname(int id);
//get address from name here
}
/*Other stuff*/
}
Why is class Reader needed
The Reader class does some in-memory caching of user details. So, I need only one object of class Reader and it will cache the user details instead of making multiple db calls.
I am using static so that it the object gets created only once. Is this the right approach or should I do something else?