在Codeigniter中访问和更改模型类中的变量

时间:2013-08-22 08:37:35

标签: php codeigniter codeigniter-2

我想访问并更改已在codeigniter中的模型类中设置的变量。

CLASS m_example extends CI_Model{
var $A;
public function __construct(){
$this->A=21;
}
public function check_v()
{
return $this->A;
}
}

所以我想在调用控制器中的函数check_v()之前更改变量$ A.

谢谢!

3 个答案:

答案 0 :(得分:1)

首先,加载模型:

$this->load->model('m_example');

访问它:

$this->m_example->a = "something";

答案 1 :(得分:1)

您可以使用getter和setter方法,如下所示,

class m_example extends CI_Model{
   private $A;

   public function __construct(){
      $this->A=21;
   }

   // get the value
   public function get_v()
   {
      return $this->A;
   }

   // set the value
   public function set_v($val){
      $this->A = $val;
   }
}

然后,

$this->load->model('m_example');
$this->m_example->set_v(50);
echo $this->m_example->get_v();

答案 2 :(得分:0)

因为您在构造函数中使用$ this->设置了A,所以它可立即用于模型中的任何方法。所以,如果$ this-> A被另一个方法更改,那么check_v()将返回最新/更改的版本

function hijackA($newvalue){

$this->A = $newvalue ;
} 
控制器中的

$this->m_example->hijackA($newvalue) ;
$a = $this->m_example->check_v() ; 

check_v()现在将返回$ newvalue