这个失败:

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

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

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

//...

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

这似乎是不必要的努力。


当前回答

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

$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] ;
}

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

其他回答

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

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

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

# use it
$my_fruits = unserialize (FRUITS);

使用某种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()功能,但是无论如何您都应该限定常量名称并避免全局变量。

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

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

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.

你可以这样定义

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

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