Welcome Guest, Not a member yet? Register   Sign In
How to set a variable in Construct, or outside of Method?
#1

[eluser]dhall[/eluser]
I am trying to set a variable that will be used in every method of my controller class. Instead of having to set it in each method, I figured I could set it in my construct, but that doesn't appear to be working correctly. What am I doing wrong... or is it even possible? Sorry if this is simple, I am very new to all this CI and coding stuff in general.
Thanks for the help!

Code:
class Account_check_model extends CI_Model {
  
  //set user_id variable
    public $user_id;
    
function __construct()
{
  parent::__construct();
  $user_id = $this->session->userdata('user_id');
}
    
  //check if activity type has been set
  public function check_activity()
  {
    
    $q = $this->db->where('user_id', $user_id)
                  ->limit(1)
                  ->get('u_act_types');
                  
    return $q;

  }

If I set $user_id inside my method it works just fine.
#2

[eluser]mudshark[/eluser]
Within your constructor and methods, reference it as $this->user_id:

Code:
function __construct()
{
  parent::__construct();
  $this->user_id = $this->session->userdata('user_id');
}
#3

[eluser]Sanjay Sarvaiya[/eluser]
Your code will look like this:

Code:
class Account_check_model extends CI_Model {
  
  //set user_id variable
    public $user_id;
    
function __construct()
{
  parent::__construct();
  $this->user_id = $this->session->userdata('user_id');
}
    
  //check if activity type has been set
  public function check_activity()
  {
    
    $q = $this->db->where('user_id', $this->user_id)
                  ->limit(1)
                  ->get('u_act_types');
                  
    return $q;

  }
#4

[eluser]sanir[/eluser]
try this
Code:
$this->user_id;


Thanks,
Nasir Ranta




Theme © iAndrew 2016 - Forum software by © MyBB