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?
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?
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']);
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.
$colors = array("red","blue","green") will be just fine.