get_instance 在 codeigniter 辅助函数中不起作用

get_instance is not working in codeigniter helper function

我想在 Codeigniter.

的辅助函数中 return 一个 csrf

但是 $this 键根据 this post

不起作用

我尝试使用 $CI =& get_instance(); ,但给了我未定义的变量:CI

请看下面的代码


    if ( !function_exists('refresh_token')){

    $CI =& get_instance(); 
        function refresh_token(){
            return $CI->security->get_csrf_hash() ; 
        }
    }

控制器:

public function delete_data(){

     $token = refresh_token(); 
              $array = array(
                      $this->security->get_csrf_token_name() => $token,
                      'data'=> "hi",
              );
              echo json_encode($array);  


}

错误:

A PHP Error was encountered
Severity: Notice

Message: Undefined variable: CI

我看到很多post,他们都推荐使用get_instance(),但如果有什么不对的地方请教我,谢谢。

函数在 PHP 中有自己的作用域,您必须将 CI 传递到您的函数中或在您的函数中声明它

例如

if ( !function_exists('refresh_token'))
{
    function refresh_token()
    {
        $CI = get_instance();
        return $CI->security->get_csrf_hash() ; 
    }
}

Take a look at https://www.php.net/manual/en/language.variables.scope.php for more informations