Kohana Model - adding additional properties

南楼画角 提交于 2019-12-24 08:28:14

问题


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.



来源:https://stackoverflow.com/questions/14805258/kohana-model-adding-additional-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!