这个失败:

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

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

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

//...

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

这似乎是不必要的努力。


当前回答

这就是我用的。它类似于soulmerge提供的示例,但是通过这种方式,您可以获得整个数组或数组中的单个值。

class Constants {
    private static $array = array(0 => 'apple', 1 => 'orange');

    public static function getArray($index = false) {
        return $index !== false ? self::$array[$index] : self::$array;
    }
}

像这样使用它:

Constants::getArray(); // Full array
// OR 
Constants::getArray(1); // Value of 1 which is 'orange'

其他回答

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

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

是的,你可以将数组定义为常量。从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"
?>

参考此链接

有一个快乐的编码。

甚至可以与关联数组工作..例如在课堂上。

class Test {

    const 
        CAN = [
            "can bark", "can meow", "can fly"
        ],
        ANIMALS = [
            self::CAN[0] => "dog",
            self::CAN[1] => "cat",
            self::CAN[2] => "bird"
        ];

    static function noParameter() {
        return self::ANIMALS[self::CAN[0]];
    }

    static function withParameter($which, $animal) {
        return "who {$which}? a {$animal}.";
    }

}

echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
echo Test::withParameter(
    array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
);

// dogs can bark.
// who can fly? a bird.

如果您使用的是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'));