2

I am using Tank_auth for user authentication in codeigniter. To check if any user is logged in or not, if he is then to get the username and id I need to use the following code in every functions of my controllers, which is very irritating.

 // If any user is logged in get his/her userid or name
    if ($this->tank_auth->is_logged_in()) {

        $data['user_id']    = $this->tank_auth->get_user_id();
        $data['username']   = $this->tank_auth->get_username();
    }

So , I was wondering if I could make life easier by putting the following code inside the function __construct() like following, but its not working.

Could you please tell me how to get it work?

Thanks in Advance :)

     function __construct()
    {
        parent::__construct();

      $this->load->helper('url');
      $this->load->library('tank_auth');


          if ($this->tank_auth->is_logged_in()) {

        $data['user_id']    = $this->tank_auth->get_user_id();
        $data['username']   = $this->tank_auth->get_username();
    }
  }
4

1 回答 1

4

if you plan to use this array only inside this controller, you can use it like this:

//outside the functions define the $data as controller class property:

private $data = array();

function __construct()
{
    parent::__construct();

    $this->load->helper('url');
    $this->load->library('tank_auth');


    if ($this->tank_auth->is_logged_in()) {
        $this->data['user_id']    = $this->tank_auth->get_user_id();
        $this->data['username']   = $this->tank_auth->get_username();
    }
}

//and then use it like 

function index(){
    $this->load->view("something.php",$this->data);
}
于 2012-05-20T10:01:52.727 回答