Constant containing Array (array)

2

When I try to define a constant as an Array it gives error.

define('COLORS', ['red', 'blue', 'green']);

Is there any way to define an Array in the value of a constant?

    
asked by anonymous 20.06.2015 / 03:50

3 answers

3

Before PHP 5.6:
It is possible to play a game using the functions serialize() and unserialize() :

define('COLORS', serialize(['red', 'blue', 'green']));
unserialize(COLORS);


As of PHP 5.6:
As mentioned bfavaretto , the PHP documentation tells us this:

  

Until PHP 5.6, only scalar data (boolean, integer, float, and string) can be put into constants. As of PHP 5.6, you can also use an array as a constant value. It is allowed to use a resource as a constant value, but should be avoided as it may cause unexpected results.

You can define a constant containing an array directly like this:

const COLORS = ['red', 'blue', 'green'];

NOTE: I did some testing and realized that the values in the Array defined in constants must also be scalar or other Array. Eg: This is NOT allowed: const CLASSES = ['anyClass' => new anyClass()];


Only from PHP 7.0 that is expected to come out in November 2015, it will be possible to define an Array directly in the define() function as follows:

define('COLORS', ['red', 'blue', 'green']);
    
20.06.2015 / 04:17
3

The manual responds :

  

Until PHP 5.6, only scalar data (boolean, integer, float, and string) can be put into constants. As of PHP 5.6, you can also use an array as a constant value. It is allowed to use a resource as a constant value, but should be avoided as it may cause unexpected results.

    
20.06.2015 / 04:04
-1
$colors = array("red","blue","green") will be just fine.
    
20.06.2015 / 04:00