get_instance在codeigniter助手功能中不起作用

问题描述 投票:0回答:1

我想在codeigniter的辅助函数中返回一个csrf。

但是根据这篇文章,$ this键不起作用,Can CodeIgniter Helper Functions use database functions?

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

请参见以下代码

if ( !function_exists('refresh_token')){

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

controller:

public function delete_data(){

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


}

错误:遇到PHP错误严重性:通知

消息:未定义变量:CI

[我看到很多帖子,他们都建议使用get_instance(),但如果有事请教我,谢谢。

php codeigniter helper
1个回答
0
投票

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

例如

if ( !function_exists('refresh_token'))
{
    function refresh_token()
    {
        $CI = get_instance();
        return $CI->security->get_csrf_hash() ; 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.