blob: f7c87011b46434a88c3e1f2bd1b814cd8d80a8e8 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001##########################
2Creating Ancillary Classes
3##########################
4
5In some cases you may want to develop classes that exist apart from your
6controllers but have the ability to utilize all of CodeIgniter's
7resources. This is easily possible as you'll see.
8
9get_instance()
10===============
11
12**Any class that you instantiate within your controller functions can
13access CodeIgniter's native resources** simply by using the
14get_instance() function. This function returns the main CodeIgniter
15object.
16
17Normally, to call any of the available CodeIgniter functions requires
18you to use the $this construct::
19
Derek Jonesaf8da302011-10-05 17:40:07 -050020 $this->load->helper('url');
21 $this->load->library('session');
22 $this->config->item('base_url');
23 // etc.
Derek Jones8ede1a22011-10-05 13:34:52 -050024
25$this, however, only works within your controllers, your models, or your
26views. If you would like to use CodeIgniter's classes from within your
27own custom classes you can do so as follows:
28
29First, assign the CodeIgniter object to a variable::
30
31 $CI =& get_instance();
32
33Once you've assigned the object to a variable, you'll use that variable
34*instead* of $this::
35
Derek Jonesaf8da302011-10-05 17:40:07 -050036 $CI =& get_instance();
37
38 $CI->load->helper('url');
39 $CI->load->library('session');
40 $CI->config->item('base_url');
41 // etc.
Derek Jones8ede1a22011-10-05 13:34:52 -050042
43.. note:: You'll notice that the above get_instance() function is being
44 passed by reference::
45
Derek Jonesaf8da302011-10-05 17:40:07 -050046 $CI =& get_instance();
Derek Jones8ede1a22011-10-05 13:34:52 -050047
48 This is very important. Assigning by reference allows you to use the
49 original CodeIgniter object rather than creating a copy of it.