user2744131
user2744131

Reputation: 11

Codeigniter 3 with get_instance(); in hook file

I have a class in hook folder like this

class CheckAuth {
    protected $CI;

    public function __construct()
    {
        $this->CI = get_instance();
    }
    public function check()
    {
        $router =& load_class('Router', 'core');
        // $controller = $this->CI->router->class;
        $controller = $router->fetch_class();
        $method     = $router->fetch_method();

        if($controller!='auth')
        {
            echo $this->CI->userdata('admin_id');
        }
    }
}

I show error when I get a session

Fatal error: Call to a member function userdata() on a non-object $this->CI return null.

Upvotes: 1

Views: 2760

Answers (2)

Aleksandar Stojilkovic
Aleksandar Stojilkovic

Reputation: 497

That's because CI isn't loaded yet in some hooks points (pre_controller, pre_system). You are probably trying to load class in some of these.

Upvotes: 1

Keval Rathi
Keval Rathi

Reputation: 986

Try this it will work.

    public function __construct()
    {

    }
    public function check()
    {
        $this->CI = get_instance();

        $router =& load_class('Router', 'core');
        // $controller = $this->CI->router->class;
        $controller = $router->fetch_class();
        $method     = $router->fetch_method();

        if($controller!='auth')
        {
            echo $this->CI->userdata('admin_id');
        }
    }

Upvotes: 1

Related Questions