CI的路由器错误

时间:2014-02-06 04:13:56

标签: php codeigniter

我正在尝试从以下行获取当前控制器的名称:

$this->router->fetch_class();

我在这里发现了这一行:

https://gist.github.com/svizion/2325988

这就是我试图在钩子中使用它的方法。

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Sys_prescript {
    public function is_logged_in()
    {
        $public_access = array('login', 'registration');    
        if (!in_array($this->router->fetch_class(), $public_access)) 
        {
            $user_id = $this -> session -> userdata('user_id');
            if (($user_id == FALSE) || (is_numeric($user_id) == FALSE) && (strlen($user_id) < 5))
            {
                redirect('login');
            }
        }
    }
}

唯一的问题是我遇到以下错误。

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Sys_prescript::$router
Filename: controllers/sys_prescript.php
Line Number: 9

Fatal error: Call to a member function fetch_class() on a non-object in...

1 个答案:

答案 0 :(得分:1)

我没有测试过代码,但请尝试:

class Sys_prescript {
private $CI;

public function is_logged_in(){
        $this->CI =& get_instance();
        $public_access = array('login', 'registration');    
        if (!in_array($this->CI->router->fetch_class(), $public_access)) 
        {
            $user_id = $this->CI -> session -> userdata('user_id');
            if (($user_id == FALSE) || (is_numeric($user_id) == FALSE) && (strlen($user_id) < 5))
            {
                redirect('login');
            }
        }
    }
}

要访问CI的单例实例,请在post_controller_constructor中调用您的挂钩,而不是在pre_controller中调用它。在实例化控制器之后,但在任何方法调用发生之前立即调用post_controller_constructor