php 如何在 codeigniter 控制器中访问自定义配置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26871797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:05:32  来源:igfitidea点击:

How to access custom config variable in codeigniter controller

phpcodeigniter

提问by user61629

I have a codigniter project with a custom config file called

我有一个带有自定义配置文件的 codigniter 项目,名为

application/config/my_config_variables.php:

This contains

这包含

<?php
$config['days'] = 20;

in :

在 :

 application/config/autoload.php

I've added:

我已经添加:

$autoload['config'] = array('my_config_variables');

when I try to access this in my controller using:

当我尝试使用以下方法在我的控制器中访问它时:

 echo $this->$config['new_daily_contacts'];

I get:

我得到:

Fatal error: Cannot access empty property.

What am I doing wrong?

我究竟做错了什么?

addendum:

附录:

In my controller I've added:

在我的控制器中,我添加了:

 // An alternate way to specify the same item:
            $my_config = $this->config->item('my_config_variables',true);
            var_dump($my_config);

this outputs FALSE -- why?

这输出 FALSE - 为什么?

回答by slapyo

Look at the config documentationon Codeigniter.

查看有关 Codeigniter的配置文档

echo $this->config->item('new_daily_contacts');

That will try to grab $config['new_daily_contacts']but from your post it looks like you only have $config['days']in your config file. But this should get you pointed in the right direction.

那将尝试抓取,$config['new_daily_contacts']但从您的帖子看来$config['days'],您的配置文件中只有它。但这应该让你指向正确的方向。

Alternate Way

替代方式

With the alternate way you're trying to load the config, but you're using the item method, not the load method. On the item method, the 2nd parameter is the index you want to reference in the config array. For instance. With your example above.

通过另一种方式,您尝试加载配置,但您使用的是 item 方法,而不是 load 方法。在 item 方法中,第二个参数是您要在 config 数组中引用的索引。例如。以你上面的例子。

$my_config = $this->config->load('my_config_variables', true);
var_dump($my_config);
$days = $this->config->item('days', 'my_config_variables');

Because passing true as the 2nd parameter on the load method will create an index with the same name as the config file. This helps avoid any conflicts if there happen to be other config files that contain the same config name.

因为在 load 方法上将 true 作为第二个参数传递将创建一个与配置文件同名的索引。如果碰巧有其他配置文件包含相同的配置名称,这有助于避免任何冲突。

$config['days'];becomes $config['my_config_variables']['days']

$config['days'];变成 $config['my_config_variables']['days']

In order to access that config variable you have to pass the index in the item method.

为了访问该配置变量,您必须在 item 方法中传递索引。

https://github.com/bcit-ci/CodeIgniter/blob/2.1-stable/system/core/Config.php#L189

https://github.com/bcit-ci/CodeIgniter/blob/2.1-stable/system/core/Config.php#L189