I’m checking if a user is logged in. If they are I 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
$datain the view and$datadoes not contain$user_nameJust befor loading your view you should do something like below so that these variables are available in the view.
Edit :
Declare
$dataas a global variable ie just before initializing constructor as shown below –protected $data;Then use
$dataas$this->dataeverywhere so if it is initialized with username in one function then it will be available in all functions too.