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:41

I agree with eyze, constants tend to be single value values needed for the entire life of your application. You might think about using a configuration file instead of constants for this sort of thing.

If you really need constant arrays, you could use naming conventions to somewhat mimic arrays: for instance DB_Name, DB_USER, DB_HOST, etc.

查看更多
唯独是你
3楼-- · 2019-01-01 06:42

Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.

查看更多
无与为乐者.
4楼-- · 2019-01-01 06:44

You can define like this

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

$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
查看更多
浮光初槿花落
5楼-- · 2019-01-01 06:46

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));
查看更多
与风俱净
6楼-- · 2019-01-01 06:47

NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

You can also serialize your array and then put it into the constant:

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

# use it
$my_fruits = unserialize (FRUITS);
查看更多
长期被迫恋爱
7楼-- · 2019-01-01 06:48

You can store them as static variables of a class:

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

If you don't like the idea that the array can be changed by others, a getter might help:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();

EDIT

Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

$x = Constants::getArray()['index'];
查看更多
登录 后发表回答