【问题标题】:Access and change a variable in model class in Codeigniter在 Codeigniter 中访问和更改模型类中的变量
【发布时间】:2013-08-22 08:37:35
【问题描述】:

我想访问和更改已在 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。

谢谢!

【问题讨论】:

  • 我希望您知道,从 5.0 开始,您应该在定义变量时使用 publicprotectedprivate,而不是 var
  • 感谢@tereško,我从来没有认真对待过。
  • @p.vansia 你能解释一下吗?
  • 实际上,还有一件过时的事情,在您的示例中不存在,但在 CodeIgniter 的代码中到处都是:通过引用分配对象。使用$CI =& get_instance()(或类似的通过引用分配对象)被认为是过时的,并且在 PHP 5.x 中可能会导致内存泄漏,因为它会干扰重新计数。请参阅this lecture 了解更多信息。
  • 你一直在燃烧 codeigniter 并试图劫持线程。请停下来。

标签: php codeigniter codeigniter-2


【解决方案1】:

首先,加载模型:

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

访问它:

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

【讨论】:

    【解决方案2】:

    可以如下使用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();
    

    【讨论】:

      【解决方案3】:

      因为你已经用 $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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 1970-01-01
        • 2016-07-20
        相关资源
        最近更新 更多