【问题标题】:get_instance is not working in codeigniter helper function [duplicate]get_instance 在 codeigniter 辅助函数中不起作用 [重复]
【发布时间】:2019-11-08 11:50:46
【问题描述】:

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

但是根据this post$this 键不起作用,

我尝试使用 $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(),但如果有问题请教我提前谢谢。

【问题讨论】:

    标签: php codeigniter helper


    【解决方案1】:

    函数在 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了解更多信息

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 2020-03-01
      • 2013-07-27
      • 2019-07-20
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多