Naftali
Naftali

Reputation: 146310

Default Values for Class Variables

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

Upvotes: 5

Views: 15910

Answers (2)

umlcat
umlcat

Reputation: 4143

(1) Extended boring answer:

Json standard functions for PHP generate objects "on the fly" with their own "internal classes", so:

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

Will generate internally something like this:

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

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

NOT your "UserModel" class.

(2) Quick answer:

There are some PHP libraries, that allow you serialize and unserialize using your classes, you may want to browse the web a little bit. Sorry, I don't have the links right now.

(3) You may also want to make your own JSON methods, but its more complicated:

class UserModel {
    // ...

    public $name;
    public $surname;

    // ...

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

Cheers.

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 82028

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:

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

It has a lower footprint, and it has more of "Resolve to default" feel.

Upvotes: 3

Related Questions