本文介绍了Kohana模型-添加其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Kohana(v3.3)模型添加额外的属性.

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;
    }
}

然后我尝试设置它

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

这将返回NULL.我不明白为什么这会是一个问题.有什么我想念的吗?

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

谢谢

推荐答案

扩展__get方法

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);
   }
}

如果Newclass尚不存在,则会自动实例化它,从而立即解决两个问题.

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

这篇关于Kohana模型-添加其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:00