在PHP中传递全局配置


Passing global configurations in PHP

我有以下内容:

_CONFIG.php

<?php namespace App'go;
define('x_client_id', 'client');
define('x_client_secret', '');
define('x_username', 'ervice');

another.php

<?php namespace App'go;
include _CONFIG.php;
class goapp
{
    protected $_client_id = x_client_id;
    protected $_client_secret = x_client_secret;
    protected $_username = x_username;

这似乎没有传递或加载变量。是否有正确的方法将变量移出文件并创建主配置?

不能将类属性初始化为使用define构造定义的常量。参考手册中的这句话:

通过使用关键字public、protected或private之一,后跟一个普通的变量声明来定义它们。该声明可以包含一个初始化,但该初始化必须是一个常数值——也就是说,它必须能够在编译时求值,并且不能依赖于运行时信息才能求值。

唯一可以初始化类属性的是解释器在编译而不是运行时可用的属性。这基本上归结为,你不能将这些属性初始化为任何需要先运行其他代码才能定义的东西。

一个例外是const关键字,因为它们是在编译时计算的。