get_instance在codeigniter帮助器函数中不起作用

我想在csrf的帮助函数中返回一个Codeigniter

但是$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

我看到很多帖子,他们都建议使用get_instance(),但是如果有问题请先教我。

adsaad 回答:get_instance在codeigniter帮助器函数中不起作用

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

例如

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

看看https://www.php.net/manual/en/language.variables.scope.php了解更多信息

本文链接:https://www.f2er.com/3138174.html

大家都在问