Let us say I have a class that looks like this:
class UserModel {
private $_userData;
function __construct($user_data){
$this->_userData = $user_data;
}
}
Which is called like this:
$user = json_decode('{"name":"Neal","surname":"MyLastName"}');
$the_user = new UserModel($user);
I do not want so that every time I want to get the user’s name to have to do $this->_userData->name inside the class.
Is it ok if i set a default value for name and surname, and chreate a __get() function like so:
class UserModel {
private $_userData;
private $name = 'default';
private $surname = 'default';
function __construct($user_data){
$this->_userData = $user_data;
}
function __get($var){
if(isset($this->_userData->$var))return $this->_userData->$var; // new storage
if(isset($this->$var))return $this->$var; // old storage
return null; // the default (could be a throw new Exception() instead)
}
}
Here is a demo of what I am trying to do: http://codepad.viper-7.com/cuS9Lx
I’m not sure if that is exactly how you would want to do it. Personally, if I had defaults, I would place them all on the class level, and then retrieve them that way:
It has a lower footprint, and it has more of “Resolve to default” feel.