开发者

Help w/ Codeigniter __construct()

I'm checking if a user is logged in. If they are I开发者_JAVA技巧 want to set some variables that will be available to all my functions in that class here is the code thus far. Calling $logged_in or $user_name from my view results in an undefined variable? Please help :)

<?php
class Auth extends Controller {

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

$this->load->library('form_validation');
$this->load->model('Auth_model');

  if ($this->session->userdata('logged_in') == TRUE)
  {
  $this->user_name = $this->session->userdata('user_name');
  $this->logged_in = TRUE;
  }
  else
  {
  $this->logged_in = FALSE;
  }
}


function forgot()
{  
$data['title'] = "Forgot Password";
$data['main_content'] = "auth/forgot";

$this->load->view('template', $data);
}

    /* My view file */

    <?php echo $user_name; // results in undefined variables ?>


It is because you have passed $data in the view and $data does not contain $user_name

Just befor loading your view you should do something like below so that these variables are available in the view.

$data['user_name'] = $this->user_name;
$data['logged_in'] = $this->logged_in.
$this->load->view('template', $data);

Edit :

Declare $data as a global variable ie just before initializing constructor as shown below -

protected $data;

Then use $data as $this->data everywhere so if it is initialized with username in one function then it will be available in all functions too.


An even easier way to do this in your view, instead of using:

echo $user_name; // results in undefined variables

use:

$this->session->userdata('user_name') ? $this->session->userdata('user_name') : '';

In simple terms, the above statement checks if user_name is set in the session, and if it is, it displays the user_name straight from the session, or else displays blank. With this you will need to make sure that the session var user_name is destroyed once the user logs out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜