12

我想知道在 Codeigniter 中定义应用程序常量的简洁方法。我不想更改 codeigniter 的任何本机文件。因此,我不想将其定义application/config/constants.php为当我需要迁移到较新版本的 code-igniter 时,我将无法直接复制 codeigniter 的本机文件。

我创建了一个文件application/config/my_constants.php并在那里定义了我的常量。'define('APP_VERSION', '1.0.0');'

我加载它使用$this->load->config('my_constants');

但我收到一个错误

Your application/config/dv_constants.php file does not appear to contain a valid configuration array.

请建议我一种在代码点火器中定义应用程序级常量的干净方法。

4

6 回答 6

39

不使用application/config/constants.php就是废话!那是您应该放置常量的唯一位置。如果您担心升级,请不要更改其中的文件。system

于 2012-05-08T07:46:12.717 回答
4

只是一个完整的答案。(没有一个答案显示如何使用声明的常量)

过程很简单:

  1. 定义一个常数。打开config/constants.php并添加以下行:

    define('SITE_CREATOR', 'John Doe')

  2. 在另一个文件中使用这个常量:

    $myVar = 'This site was created by '.SITE_CREATOR.' Check out my GitHub Profile'

于 2014-08-13T13:56:45.277 回答
3

define()您的 my_constants.php 文件应如下所示,而不是 using :

$config['app_version'] = '1.0.0';

不过要小心命名数组键,你不想与任何东西冲突。

如果您需要使用define(),我建议在主 index.php 文件中进行,尽管您仍然需要使用APP_VERSION来获取值。

于 2012-05-08T12:18:18.440 回答
1
    config file (system/application/config/config.php) to set configuration related variables.

    Or use 

    constant file (system/application/config/constants.php) to store site preference constants.


  =======================
  DEFINE WHAT YOU WANT
  =======================
  $config['index_page'] = 'home';
  $config['BASEPATH'] = 'PATH TO YOUR HOST';
于 2014-01-07T10:26:16.550 回答
0

请参考这个:

http://ellislab.com/forums/viewthread/56981/

将变量定义为常量并在数组上添加值

$ORDER_STATUS  = array('0'=>'In Progress','1'=>'On Hold','2'
                 =>'Awaiting Review','3'=>'Completed','4'
                 =>'Refund Requested','5'=>'Refunded');
于 2014-01-17T09:28:53.950 回答
0

您可以通过将常量添加到您自己的配置文件中来实现您的目标,例如my_config.php.

您可以将此文件保存在application/config文件夹中,如下所示: application/config/my_config.php.

为您编写的每个应用程序都有一个单独的配置文件是很常见的,因此这将很容易维护并被其他 CI 程序员理解。

您可以指示 CI 自动加载此文件,也可以根据需要手动加载它。请参阅“配置类”的 CI 手册。

于 2017-11-27T10:01:57.030 回答