如何在所有方法中使构造函数中的变量可用?

时间:2015-07-30 19:44:53

标签: php codeigniter

我是使用codeigniter并且在我的一个模型构造函数中,我有以下

public function __construct()
{
    parent::__construct();
    $DB2 = $this->load->database('std', TRUE);
}

在我的方法中:

public function get_users_groups($id=FALSE)
    {
        $this->trigger_events('get_users_group');

        //if no id was passed use the current users id
        $id || $id = $this->session->userdata('user_id');

        return $DB2->select($this->tables['users_groups'].'.'.$this->join['groups'].' as id, '.$this->tables['groups'].'.name, '.$this->tables['groups'].'.description')
                        ->where($this->tables['users_groups'].'.'.$this->join['users'], $id)
                        ->join($this->tables['groups'], $this->tables['users_groups'].'.'.$this->join['groups'].'='.$this->tables['groups'].'.id')
                        ->get($this->tables['users_groups']);
    }

我得到一个未定义的变量$ DB2可以告诉我我在做什么wrog plase?

1 个答案:

答案 0 :(得分:3)

$ DB2只能在构造函数范围内使用,它必须是类属性,如下所示:

class Whatever
{
    protected $DB2;

    public function __construct() {
        parent::__construct();
        $this->DB2 = $this->load->database('std', TRUE);
    }

    public function get_users_groups($id=FALSE)
    {
      // other code    
      $this->DB2->select( ....
      // other code
    }

}
相关问题