这个失败:

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

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

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

//...

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

这似乎是不必要的努力。


当前回答

如果您是从2009年开始看这个,并且不喜欢AbstractSingletonFactoryGenerators,那么这里有一些其他选项。

记住,数组在赋值时被“复制”,或者在本例中被返回,因此实际上每次都得到相同的数组。(参见PHP中数组的写时复制行为。)

function FRUITS_ARRAY(){
  return array('chicken', 'mushroom', 'dirt');
}

function FRUITS_ARRAY(){
  static $array = array('chicken', 'mushroom', 'dirt');
  return $array;
}

function WHAT_ANIMAL( $key ){
  static $array = (
    'Merrick' => 'Elephant',
    'Sprague' => 'Skeleton',
    'Shaun'   => 'Sheep',
  );
  return $array[ $key ];
}

function ANIMAL( $key = null ){
  static $array = (
    'Merrick' => 'Elephant',
    'Sprague' => 'Skeleton',
    'Shaun'   => 'Sheep',
  );
  return $key !== null ? $array[ $key ] : $array;
}

其他回答

如果你使用的是php7 & 7+,你也可以像这样使用fetch

define('TEAM', ['guy', 'development team']);
echo TEAM[0]; 
// output from system will be "guy"

你可以这样定义

define('GENERIC_DOMAIN',json_encode(array(
    'gmail.com','gmail.co.in','yahoo.com'
)));

$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);

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

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'];

使用爆炸和内爆函数,我们可以临时想出一个解决方案:

$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1]; 

这将回复邮件。

如果你想让它更优化,你可以定义2个函数来做重复的事情,像这样:

//function to define constant
function custom_define ($const , $array) {
    define($const, implode (',' , $array));
}

//function to access constant  
function return_by_index ($index,$const = DEFAULT_ROLES) {
            $explodedResult = explode(',' ,$const ) [$index];
    if (isset ($explodedResult))
        return explode(',' ,$const ) [$index] ;
}

希望这能有所帮助。快乐编码。

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