开发者

Is it possible to declare an array as constant [duplicate]

开发者 https://www.devze.com 2023-01-17 13:53 出处:网络
This question already has answer开发者_如何学运维s here: PHP Constants Containing Arrays? (16 answers)
This question already has answer开发者_如何学运维s here: PHP Constants Containing Arrays? (16 answers) Closed 5 years ago.

We can define a constant like

define("aconstant','avalue');

Can't we define array in this fashion like below ?

define("months",array("January", "February", ---); 


you can use const for that purpose since PHP 5.6 (via nikic).

const months = ["January", "February"];
var_dump("January" === months[0]);


UPDATE: this is possible in PHP 7 (reference)

// Works as of PHP 7
define('ANIMALS', array(
    'dog',
    'cat',
    'bird'
));
echo ANIMALS[1]; // outputs "cat"

ORIGINAL ANSWER

From php.net...

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.

$months = array("January,"February",...) will be just fine.


You can put arrays inside constants with a hack:

define('MONTHS', serialize(array('January', 'February' ...)));

But then you have to unserialize() that constant value when needed and I guess this isn't really that useful.

As an alternative, define multiple constants:

define('MONTH_1', 'January');
define('MONTH_2', 'February');
...

And use constant() function to look up the value:

echo constant('MONTH_'.$month);


No, you can't. See PHP: Syntax - Manual

Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.


You can use JSON format to keep array in string and then assign this string to constant.

$months = array("January","February","March");
define('MONTHS', json_encode($months));

When you want to use it:

$months = json_decode(MONTHS);


If you must have a constant, how about using a a delimited string and exploding into an array?

define("MONTHS", "January;February;March");
$months = explode(";",MONTHS);


As of PHP 5.6, it is possible to declare constant arrays. The linked documentation uses the example const ARR = ['a', 'b'];. You could also do const ARR = array('a', 'b');. However, in 5.6 there is an odd quirk: you can declare constant arrays using const, but not define(). This has been corrected in PHP 7.0.

0

精彩评论

暂无评论...
验证码 换一张
取 消