这个失败:

 define('DEFAULT_ROLES', array('guy', 'development team'));

显然,常量不能保存数组。解决这个问题的最好方法是什么?

define('DEFAULT_ROLES', 'guy|development team');

//...

$default = explode('|', DEFAULT_ROLES);

这似乎是不必要的努力。


当前回答

您可以将其作为JSON字符串存储在常量中。从应用程序的角度来看,JSON在其他情况下也很有用。

define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));    
$fruits = json_decode (FRUITS);    
var_dump($fruits);

其他回答

PHP 7 +。

从PHP 7开始,你可以使用define()函数定义一个常量数组:

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"

你可以将它们存储为类的静态变量:

class Constants {
    public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';

如果你不喜欢数组可以被其他人更改的想法,getter可能会有所帮助:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();

EDIT

从PHP5.4开始,甚至可以在不需要中间变量的情况下访问数组值,即以下工作:

$x = Constants::getArray()['index'];

常量只能包含标量值,我建议您存储数组的序列化(或JSON编码表示)。

如果您使用的是php5.6或以上版本,请使用Andrea Faulds的答案

我是这样用的。我希望,这将帮助其他人。

config。

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

在文件中,我需要常数。

require('config.php');
print_r(app::config('app_id'));

从PHP 5.6开始,你可以用const声明一个数组常量:

<?php
const DEFAULT_ROLES = array('guy', 'development team');

短语法也可以,正如你所期望的那样:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

如果你有PHP 7,你最终可以使用define(),就像你第一次尝试的那样:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));