PHP constant as array

Is it possible to create a group of constants and get them exactly as an array, rather than writing each constant yourself?

something like

echo MYCONST[0]; or 
echo MYCONST['name'];

      

+3


source to share


2 answers


What you are looking for is called Constant array:

it is now possible to do this with define () , but only for PHP7, However, you can do this in PHP5.6 using the const keyword and it cannot be done in lower PHP versions



here's an example:

<?php

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"

define('MYCONST', [
    'key' => "value"

    ]);

echo MYCONST['key']; // outputs "value"

      

+9


source


1. If you are using PHP7 , you can define constant as an array

.

define('MYCONST', array("someValue1","someValue2"));

      

2. Version lower than PHP7 , you can store the string as a constant, whether it can be a JSON

string or a serialized

string.



define('MYCONST', json_encode(array("someValue1","someValue2")));
define('MYCONST', serialize(array("someValue1","someValue2")));

      

To access a constant in a lower version of PHP7 (if it is a string JSON

or serialized

), you must json_decode

or unserialize

respectively.

+9


source







All Articles