这个失败:

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

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

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

//...

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

这似乎是不必要的努力。


当前回答

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

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

其他回答

是的,你可以将数组定义为常量。从PHP 5.6开始,可以将常量定义为标量表达式,也可以定义数组常量。可以将常量定义为资源,但应该避免这样做,因为这会导致意想不到的结果。

<?php
    // Works as of PHP 5.3.0
    const CONSTANT = 'Hello World';
    echo CONSTANT;

    // Works as of PHP 5.6.0
    const ANOTHER_CONST = CONSTANT.'; Goodbye World';
    echo ANOTHER_CONST;

    const ANIMALS = array('dog', 'cat', 'bird');
    echo ANIMALS[1]; // outputs "cat"

    // Works as of PHP 7
    define('ANIMALS', array(
        'dog',
        'cat',
        'bird'
    ));
    echo ANIMALS[1]; // outputs "cat"
?>

参考此链接

有一个快乐的编码。

使用某种ser/deser或encode/decode技巧看起来很难看,并且要求您在尝试使用常量时记住您到底做了什么。我认为class private static variable with accessor是一个不错的解决方案,但我会给你一个更好的。只要有一个返回常量数组定义的公共静态getter方法。这只需要最少的额外代码,并且数组定义不会被意外修改。

class UserRoles {
    public static function getDefaultRoles() {
        return array('guy', 'development team');
    }
}

initMyRoles( UserRoles::getDefaultRoles() );

如果你真的想让它看起来像一个已定义的常量,你可以给它一个全大写的名字,但是记住在名字后面加上'()'括号会让人困惑。

class UserRoles {
    public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}

//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );

我认为您可以将方法设置为全局的,以便更接近您所要求的define()功能,但是无论如何您都应该限定常量名称并避免全局变量。

如果您是从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"

PHP 5.6+引入了const数组——参见Andrea Faulds的回答。

你也可以序列化你的数组,然后把它放入常量:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);