Kohana Model - adding additional properties

2019-07-29 09:44发布

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

标签: php class kohana
1条回答
Summer. ? 凉城
2楼-- · 2019-07-29 10:25

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.

查看更多
登录 后发表回答