Skip to content
Advertisement

Codeigniter variables from constructor are undefined

I’m using CI’s Auth Tank library to query records for certain users.

The variable $user_id = tank_auth->get_user_id(); grabs the user id from the session. I want to pull records where user_id = $user_id.

From what I understood, constructors can load variables each time a class is initiated. Sort of like global variables. So I figured I’ll set my $user_id in a model constructor so I can use it for multiple functions within the model class.

JavaScript

Next, I’m loading the model, creating an array in my controller, and sending the data to my view where I have a foreach loop.

When testing I get

Message: Undefined variable: user_id

in my model. It works however if I define the $user_id variable in my posts_read function, but I don’t want to define it in every function that needs it.

What am I doing wrong here?

Advertisement

Answer

Variable scope problem. You should create class-level variables so that it is available in other functions as well like this:

JavaScript

Notice the addition of $user_id after class declaration which is later used with $this->user_id 🙂

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement