We get an error message “Fatal error: Using $this when not in object context” when access CodeIgniter resources within your helper functions or custom library.
For example, we have a helper function called check_login in helpers/site_helper.php that calls session library to determine if a user logged in or not.
helpers/site_helper.php
1 2 3 4 5 6 7 8 9 10 | <?php function check_login() { if($this->session->userdata('id') == "" || $this->session->userdata('email') == "") { redirect(base_url() . 'index.php/auth/login','location'); exit(); } } ?> |
This function will produce a error message:
Fatal error: Using $this when not in object context in D:\_$projects\2. Internal\2.4 4rapiddev.com\_Development\Webfiles\demo\PHP\CodeIgniter\application\helpers\site_helper.php on line 4 |
In order to resolve Fatal error: Using $this when not in object context issue, we will need to assign the CodeIgniter object to a variable like this:
$ci = get_instance();
… then use $ci variable instead of $this.
So the helper function above should be like this:
1 2 3 4 5 6 7 8 9 10 11 | <?php function check_login() { $ci = get_instance(); if($ci->session->userdata('id') == "" || $ci->session->userdata('email') == "") { redirect(base_url() . 'index.php/auth/login','location'); exit(); } } <?> |