Kohana Model - adding additional properties

2019-07-29 09:46发布

问题:

I am trying to add extra properties to my Kohana (v3.3) model.

class Model_mymodel extends ORM {
    protected $_myvar = NULL;

    public function set_myvar() {
        $this->_myvar = new Newclass();
    }

    public function get_myvar() {
        return $this->_myvar;
    }
}

And then I try and set it

$inst = ORM::factory('mymodel', 1)->find();
$inst->set_myvar();
var_dump($inst->get_myvar());

This returns NULL. I dont see why this would be a problem. Is there something that I am missing?

Thanks

回答1:

extend the __get method

class Model_mymodel extends ORM {
   protected $_myvar = NULL;

   function __get($name) {
      if ($name === 'myvar'){
         if (!($this->_myvar instanceof Newclass){
            $this->_myvar = new Newclass;
         }
         return $this->_myvar;
      }
      return parent::__get($name);
   }
}

This way the Newclass is instantiated automatically if it doesn't exist yet, solving two problems at once.



标签: php class kohana