CodeIgniter Forums
Use function in multiple controllers - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Use function in multiple controllers (/showthread.php?tid=26330)



Use function in multiple controllers - El Forum - 01-11-2010

[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!


Use function in multiple controllers - El Forum - 01-11-2010

[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.


Use function in multiple controllers - El Forum - 01-11-2010

[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('/');}


Use function in multiple controllers - El Forum - 01-11-2010

[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!


Use function in multiple controllers - El Forum - 01-11-2010

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