这个失败:

 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);

其他回答

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

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

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

你可以这样定义

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

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

我知道这是一个有点老的问题,但这是我的解决方案:

<?php
class Constant {

    private $data = [];

    public function define($constant, $value) {
        if (!isset($this->data[$constant])) {
            $this->data[$constant] = $value;
        } else {
            trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
        }
    }

    public function __get($constant) {
        if (isset($this->data[$constant])) {
            return $this->data[$constant];
        } else {
            trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
            return $constant;
        }
    }

    public function __set($constant,$value) {
        $this->define($constant, $value);
    }

}
$const = new Constant;

我定义它是因为我需要在常量中存储对象和数组,所以我也安装了runkit到php,这样我就可以使$const变量超全局。

你可以使用它作为$const->define("my_constant",array("my","values"));或者只是$const->my_constant = array("my","values");

要获取该值,只需调用$const->my_constant;

PHP 7 +。

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

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

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