I’ve got a class which has a lot of properties, an I wanted to define getters that would selectively access the database (ie if we’ve set the property, return it, otherwise get a bunch of data from the database and store it somewhere for other class getters to access).
I stumbled upon using __get which works pretty well for this, however it only works when the property has not been defined. I like to define my properties. I think it’s neater. Even if I don’t want to write a ream of near-identical getters for them.
Is it possible to use a similar functionality that works when properties have been defined but not set?
eg This will work as desired
class AutoGetter
{
public function __get($name)
{
//do some things that justify the use of magic functions
return $name;
}
}
$o = new AutoGetter();
echo $o->nonExistantVariable;
This will echo:
nonExistantVariable
However, if I define the property
class AutoGetter
{
public $nonExistantVariable;
public function __get($name)
{
//do some things that justify the use of magic functions
return $name;
}
}
$o = new AutoGetter();
echo $o->nonExistantVariable;
This will output null, because the property $nonExistantVariable has been defined, even if it hasn’t been set.
What is it I’m looking for here? Instead of magic functions would I be better off using my constructor to dynamically create a bunch of getters?