PHP Constants Containing Arrays?

2019-01-01 05:52发布

This failed:

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

Apparently, constants can't hold arrays. What is the best way to get around this?

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

//...

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

This seems like unnecessary effort.

20条回答
残风、尘缘若梦
2楼-- · 2019-01-01 06:56

This is what I use. It is similar to the example provided by soulmerge, but this way you can get the full array or just a single value in the array.

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

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

Use it like this:

Constants::getArray(); // Full array
// OR 
Constants::getArray(1); // Value of 1 which is 'orange'
查看更多
只若初见
3楼-- · 2019-01-01 06:57

That is correct, you cannot use arrays for a constant, only scaler and null. The idea of using an array for constants seem a bit backwards to me.

What I suggest to do instead is define your own constant class and use that to get the constant.

查看更多
登录 后发表回答