Welcome Guest, Not a member yet? Register   Sign In
Use function in multiple controllers
#1

[eluser]jj135[/eluser]
Hi! I/m new to Code-Igniter. Trying to build my fist application. It's not that hard to get started... Documentation is pretty good.

I have a question: How do I create a function I can use in more than one controller? For example a logout function. Or a function that checks if a user is logged in? I can create this function in a controller itself and use it ($this->functionname()) but if I want to use this function in multiple controllers, where do I store it and how do I call it?

Thanks!
#2

[eluser]danmontgomery[/eluser]
You can use helpers in any controller once they're loaded. For example, to use the form helper,

Code:
$this->load->helper('form');
echo form_open('user/login');

Full documentation of helpers is in the user guide.
#3

[eluser]jj135[/eluser]
Thanks! I tried that. I seems to be working fot one of my function (logout). But not for another function:

"Using $this when not in object context"

What does that mean? I use this:
if ($this->session->userdata('logged_in') == FALSE) { redirect('/');}
#4

[eluser]jj135[/eluser]
Hi! I found the problem. You can not use $this in a helper. You have to use:

Code:
$CI =& get_instance();
$CI->session->userdata('logged_in')

This works!
#5

[eluser]danmontgomery[/eluser]
Correct, you can only use $this in an class method, where $this refers to the current instance of the class.




Theme © iAndrew 2016 - Forum software by © MyBB