Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Codeigniter创建和访问全局变量_Codeigniter_Codeigniter 3 - Fatal编程技术网

Codeigniter创建和访问全局变量

Codeigniter创建和访问全局变量,codeigniter,codeigniter-3,Codeigniter,Codeigniter 3,我已经做了很多研究,但是大多数源代码都可以追溯到很久以前,所以对于如何在ci3.x中进行这项工作,我有点困惑 我有一个为每个用户克隆的应用程序,它独立于所有其他实例运行。每个实例在计算费用的方式上可能不同,这就是全局变量的作用 我已成功实施了以下解决方案: *in application/config/config.php* $config['expenses_calculation'] = 'monthly'; 我现在几乎可以在任何地方访问变量,如下所示: $this->config

我已经做了很多研究,但是大多数源代码都可以追溯到很久以前,所以对于如何在
ci3.x
中进行这项工作,我有点困惑

我有一个为每个用户克隆的应用程序,它独立于所有其他实例运行。每个实例在计算费用的方式上可能不同,这就是全局变量的作用

我已成功实施了以下解决方案:

*in application/config/config.php*

$config['expenses_calculation'] = 'monthly';
我现在几乎可以在任何地方访问变量,如下所示:

$this->config->config['expenses_calculation'];
然而,我对
CI
还不熟悉,我相信必须有正确的方法来做到这一点,这不是我提供的示例


非常感谢您提供任何帮助或指导。

1。定义常数

application/config/constants.php

无论在何处,您都需要访问:

2。在控制器中定义变量

控制器:

控制器的构造函数总是先运行(在控制器中)。因此,您可以向该“全局”变量添加任何值,并且您可以从控制器的任何位置轻松访问该值

print $this->expenses_calculation; // output will be: "monthly"

如果您打算提供如何处理计算的默认\说明,那么您所做的是完全可以接受的。我建议您以这种方式访问变量

$calc_method = $this->config->item('expenses_calculation');
这样做的好处是,如果项目不存在,
item('expenses\u calculation')
将返回NULL

但是如果
$this->config->config['expenses\u calculation'不存在将抛出“未定义索引”PHP错误

class Page extends CI_Controller
{
    private $expenses_calculation = "";

    function __construct()
    {
        parent::__construct();

        $this->expenses_calculation = "monthly"; // you can fetch anything from your database or you do anything what you want with this variable
    }
}
print $this->expenses_calculation; // output will be: "monthly"
$calc_method = $this->config->item('expenses_calculation');