Codeigniter 创建和访问全局变量
Codeigniter create and access global variable
我做了相当多的研究,但是大部分资料都可以追溯到很久以前,所以我对如何在 CI 3.x
.
中做到这一点感到有点困惑
我有一个为每个用户克隆并独立于所有其他实例运行的应用程序。每个实例计算费用的方式可能不同,这就是全局变量的用武之地。
我已经快速实施了以下解决方案:
*in application/config/config.php*
$config['expenses_calculation'] = 'monthly';
我现在几乎可以像这样在任何地方访问变量:
$this->config->config['expenses_calculation'];
但是,我是 CI
的新手,我相信必须有正确的方法来做到这一点,这不是我提供的示例。
非常感谢任何帮助或指导。
1.定义常量
application/config/constants.php
define('EXPENSES_CALCULATION', 'monthly');
任何地方,你需要访问的地方:
print EXPENSES_CALCULATION; // output will be: "monthly"
2。在控制器中定义变量
控制器:
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
}
}
控制器的构造函数总是 运行 在其他任何事情之前(在控制器中)。因此,您可以向该 "global" 变量添加任何值,并且您可以从您的控制器在任何地方轻松访问该值。
print $this->expenses_calculation; // output will be: "monthly"
如果您的目的是提供默认的\描述如何处理计算,那么您所做的是完全可以接受的。我建议您以这种方式访问变量。
$calc_method = $this->config->item('expenses_calculation');
这样做的好处是如果项目不存在,item('expenses_calculation')
将 return NULL。
但如果 $this->config->config['expenses_calculation'];
不存在,则会抛出 "Undefined index" PHP 错误。
我做了相当多的研究,但是大部分资料都可以追溯到很久以前,所以我对如何在 CI 3.x
.
我有一个为每个用户克隆并独立于所有其他实例运行的应用程序。每个实例计算费用的方式可能不同,这就是全局变量的用武之地。
我已经快速实施了以下解决方案:
*in application/config/config.php*
$config['expenses_calculation'] = 'monthly';
我现在几乎可以像这样在任何地方访问变量:
$this->config->config['expenses_calculation'];
但是,我是 CI
的新手,我相信必须有正确的方法来做到这一点,这不是我提供的示例。
非常感谢任何帮助或指导。
1.定义常量
application/config/constants.php
define('EXPENSES_CALCULATION', 'monthly');
任何地方,你需要访问的地方:
print EXPENSES_CALCULATION; // output will be: "monthly"
2。在控制器中定义变量
控制器:
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
}
}
控制器的构造函数总是 运行 在其他任何事情之前(在控制器中)。因此,您可以向该 "global" 变量添加任何值,并且您可以从您的控制器在任何地方轻松访问该值。
print $this->expenses_calculation; // output will be: "monthly"
如果您的目的是提供默认的\描述如何处理计算,那么您所做的是完全可以接受的。我建议您以这种方式访问变量。
$calc_method = $this->config->item('expenses_calculation');
这样做的好处是如果项目不存在,item('expenses_calculation')
将 return NULL。
但如果 $this->config->config['expenses_calculation'];
不存在,则会抛出 "Undefined index" PHP 错误。