首页 > 解决方案 > 如何在 CodeIgniter 中创建全局变量?

问题描述

场景: 我有一个 JSON 文件,它在一个对象中包含大约 4,000 个键值对。在 CodeIgniter 辅助函数中,我获取此文件的内容,用于json_decode()将内容转换为 PHP 对象并返回该对象。

代码片段

function get_characters()
{
    $json_url = base_url('keywords.json'); // path to JSON file
    $json_data = file_get_contents($json_url); // put the contents of the file into a variable
    return json_decode($json_data); // decode and return the JSON content
}

问题 1:由于每次调用该函数都会读取 JSON 文件,因此一遍又一遍地调用此函数会影响性能吗?

问题 2:如果它妨碍了性能,我如何将这个函数的输出一次存储在一个全局变量中,以便我可以在我的应用程序中使用它?还是有更好的解决方案?

提前致谢!

标签: phpjsoncodeigniter

解决方案


您应该在问题中包含您的代码片段。不用担心,我有一个答案给你。我希望它可以帮助你完成这项工作。

答案1:显然。

答案2:当然有很多方法可以做到这一点。您应该将输出分配给 CI 超全局变量,如下所示:

//Your helper function may look like..
if (!function_exists('load_my_json_file'))
{
    function load_my_json_file()
    {
        $my_json = file_get_contents('./my_json.json');
        $my_json_obj = json_decode($my_json);

        //Grab the CodeIgniter native resource
        $CI = & get_instance();
        $CI->my_json_obj = $my_json_obj;
        return true;
    }

}

现在您将能够通过$this->my_json_obj从控制器、模型或视图调用来访问您的 json 对象。

下面给出一个关于如何调用辅助函数的示例:

//app/core/MY_Controller.php
class MY_Controller extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        //Load your helper
        $this->load->helper('common');
        //Call the json loader function
        load_my_json_file();
    }

}
//controllers/Welcome.php
class Welcome extends MY_Controller
{

    public function index()
    {
        var_dump($this->my_json_obj);
        exit();
        $this->load->view('welcome_message');
    }
}

推荐阅读