Default Values ​​for Class Variables

Say I have a class that looks like this:

class UserModel {
    private $_userData;
    function __construct($user_data){
          $this->_userData = $user_data;
    }
}

What is called like this:

$user = json_decode('{"name":"Neal","surname":"MyLastName"}'); 
$the_user = new UserModel($user);

I don’t want every time I want the username to be executed $this->_userData->nameinside the class.

Well, if I set the default value for the first and last name and create a function __get()as follows:

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'm trying to do: http://codepad.viper-7.com/cuS9Lx

+5
source share
2 answers

I'm not sure that is exactly what you want to do. Personally, if I had the default values, I would put them all at the class level, and then restore them as follows:

class Foo
{
     static $bar = 1;
     private $_udata;
     public function __get($a)
     {
          return (isset($this->_udata->$a))?
                    $this->_udata->$a:
                    self::$$a; // NOTE DOUBLE $!
     }
};
$f = new Foo(); echo $f->bar; // 1

, "Resolve to default".

+3

(1) :

Json PHP " " " ", :

$user = json_decode('{"name":"Neal","surname":"MyLastName"}'); 

- :

//class object(stdClass)#1 (1) {
class tempclass343434 {
    public $name;
    public $surname;
}

$user = new tempclass343434();
$user->name = "Neal";
$user->surname = "MyLastName";

UserModel.

(2) :

PHP, , -. , .

(3) JSON, :

class UserModel {
    // ...

    public $name;
    public $surname;

    // ...

    /* string */ function ExportToJson() { $Result = "";  ... return $Result; }
    /* void */ function ImportToJson(/* String */ JSONValue) { ... }
} // UserModel 

.

0

All Articles